diff --git a/.githooks/pre-push b/.githooks/pre-push new file mode 100755 index 00000000..73fdcccd --- /dev/null +++ b/.githooks/pre-push @@ -0,0 +1,27 @@ +#!/bin/sh +# Repository-local guard. Git supplies the remote name and resolved push URL. +set -eu + +reject_original() +{ + normalized=$(printf '%s' "$1" | tr '[:upper:]\\' '[:lower:]/') + case "$normalized" in + *id-software/wolf3d*|*id-software:wolf3d*) + printf '%s\n' 'Push rejected: the original id-Software/wolf3d repository is fetch-only.' >&2 + exit 1 + ;; + esac +} + +reject_original "${1-}" +reject_original "${2-}" +# Also check every configured push destination (including Git URL rewrites). +if destinations=$(git remote get-url --push --all "${1-}" 2>/dev/null); then + old_ifs=$IFS + IFS=' +' + for destination in $destinations; do + reject_original "$destination" + done + IFS=$old_ifs +fi diff --git a/.github/workflows/validation.yml b/.github/workflows/validation.yml new file mode 100644 index 00000000..ff9d9115 --- /dev/null +++ b/.github/workflows/validation.yml @@ -0,0 +1,78 @@ +name: Validation + +on: + push: + branches: [docs/revival-roadmap-and-validation] + pull_request: + branches: [master] + workflow_dispatch: + +permissions: + contents: read + +jobs: + r06-mandatory-synthetic: + name: R0.6 mandatory synthetic (CPU+graphics+runner) + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + SDL_SDK: ${{ github.workspace }}/.cache/SDL + WOLF3D_BINARY: ${{ github.workspace }}/build/cart-sdl/linux/wolf3d-revive + SDL_VIDEODRIVER: dummy + SDL_RENDER_DRIVER: software + SDL_AUDIODRIVER: dummy + steps: + - uses: actions/checkout@v4 + + - name: Cache SDL3 build + id: cache-sdl + uses: actions/cache@v4 + with: + path: ${{ env.SDL_SDK }} + key: sdl3-linux-${{ runner.os }}-release-3.2.8 + + - name: Build SDL3 (if cache miss) + if: steps.cache-sdl.outputs.cache-hit != 'true' + run: | + set -euxo pipefail + sudo apt-get update + sudo apt-get install -y --no-install-recommends cmake ninja-build build-essential pkg-config + git clone --depth 1 --branch release-3.2.8 https://github.com/libsdl-org/SDL.git /tmp/sdl-src + cmake -S /tmp/sdl-src -B /tmp/sdl-build -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DSDL_SHARED=OFF \ + -DSDL_STATIC=ON \ + -DSDL_TEST_LIBRARY=OFF \ + -DSDL_UNIX_CONSOLE_BUILD=ON \ + -DCMAKE_INSTALL_PREFIX="$SDL_SDK" + cmake --build /tmp/sdl-build -j2 + cmake --install /tmp/sdl-build + # Also provide build/libSDL3.a path expected by tests + mkdir -p "$SDL_SDK/build" + cp /tmp/sdl-build/libSDL3.a "$SDL_SDK/build/libSDL3.a" + + - name: Verify prerequisites + run: | + set -euxo pipefail + python3 --version + gcc --version | head -1 + test -f "$SDL_SDK/build/libSDL3.a" + + - name: Build application (clean checkout, no proprietary assets) + run: | + set -euxo pipefail + ./tools/ci_build_app.sh "$WOLF3D_BINARY" + test -x "$WOLF3D_BINARY" || test -f "$WOLF3D_BINARY" + + - name: Run R0.6 mandatory synthetic validation + run: | + set -euxo pipefail + python3 tools/validation/run.py R0.6 + + - name: Upload validation evidence on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: r06-validation-evidence + path: build/validation/ + if-no-files-found: warn diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..fa2d710e --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Keep commercial data and personal saves outside version control. +/data/ +/game-data/ +*.[Ww][Ll][16] +*.[Ss][Oo][Dd] +*.[Ss][Dd][123Mm] +*.[Ww][Ll][Ff] +/build/ +/dist/ +/vendor/ +*.o +*.obj +*.exe +*.dll +*.so +*.so.* +*.a +*.lib +__pycache__/ +# Local diagnostic captures can contain commercial game artwork. +*.bmp +*.ppm +[Ss][Ii][Gg][Nn][Oo][Nn].[Rr][Aa][Ww] + +# Third-party assets are local research inputs only. +# Do not commit or redistribute them without verified permissions. +/3rdparty/ +# Also block the previous ECWolf location against accidental recommits. +/asset/ECWolf_RMST/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..fee8ed23 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,48 @@ +# AGENTS.md — Wolf3D Revive agent working agreement + +Applies to Codex, Gemma/OpenCode and any automation working in this repository. Read this file **before changing code**. This is the project's durable, vendor-neutral agent entry point, not a claim that any agent automatically remembers previous chats. + +## Source of truth and work order + +1. Read `docs/plan.md`, then the selected `docs/milestones/Rn/PLAN.md` and its revision contract (when created). +2. Read `docs/validation/TEST_STRATEGY.md` and `docs/automation/PLAYBOOK.md` to discover existing workflows. +3. Inspect actual source/config/tests for the selected change, then use recorded commands; do not assume planned scripts already exist. +4. Work on one approved revision; document a scope change before expanding it. +5. Execute focused tests, required regression, and relevant safety checks. Produce evidence, not assertions. +6. Update the relevant validation report and playbook if workflow knowledge changed; report unfinished checks honestly. + +## Engineering boundaries + +- C11 + SDL3 + existing CART configuration; preserve Classic 4:3 and Enhanced widescreen unless the revision explicitly changes them. +- No large rewrite or new dependency to solve a local defect; prefer small modules with justified ownership. +- Original-game work: respect code licences and document asset provenance; do not copy or package uncleared Wolfenstein material. +- Workshop: same map representation and native C world operations as gameplay, headless testable; do not make authoring functionality depend on UI callbacks. +- Deterministic simulation, bounded memory and graceful handling of malformed files are default requirements. +- Keep generated binaries, logs, screenshots and temporary artefacts out of source control unless a review explicitly requires golden fixtures. + +## Stop agents repeating work + +**Search before solving.** Check `docs/automation/PLAYBOOK.md`, `tools/`, `tests/`, past revision validation and existing commands before creating a helper or troubleshooting a recurring failure. + +**Capture a recurring task.** When you see the same multi-step sequence a second time, or it is clearly going to repeat across revisions/agents, add a reusable, reviewed command/script or a deterministic documented procedure as part of the change (or open a separately scoped task if implementation is not approved). Examples: clean build setup, smoke runs, screenshot capture, validation, test fixture generation, PR review evidence and reproducible failure diagnosis. + +**Automate only when safe.** Scripts must be local, deterministic where feasible, idempotent for setup, non-destructive by default, with explicit arguments, prerequisite checks, clear progress, bounded runtime, exit status and an output/log path. No silently downloading dependencies, disabling sanitizers, force-pushing, deleting branches, merging PRs, removing user files, or silently changing milestone status. Operations that mutate remote state require explicit approval. + +**Avoid duplicate helper scripts.** Extend the canonical tool instead of creating `test2.sh`, `validate-new.py`, etc. Add a targeted test for new tooling; record how to invoke it in the playbook. + +**Make the next agent independent.** End each revision with: current state, commit/branch, modified files, tests run and exit status, outstanding blockers, exact next command and updated references. Do not rely on chat history as the only record. + +## Truthful gate states + +For every required acceptance criterion use `PASS`, `FAIL`, `PARTIAL`, or `NOT RUN`. A compile is not a test pass. A skipped graphics, sanitizer or human usability check is not a pass. Log a hung stage and reason. Do not claim a milestone is completed until its explicit gates and review are satisfied. + +## Repository entry points + +- `docs/plan.md`: roadmap and revision ordering +- `docs/milestones/R0/PLAN.md`: first implementation and baseline acceptance contract +- `docs/validation/TEST_STRATEGY.md`: planned test layers and evidence +- `docs/automation/PLAYBOOK.md`: reusable procedures, script conventions and automation backlog +- `docs/ORIGINAL_CONTENT_AND_IP.md`: copyright/asset separation +- `docs/WORKSHOP_DESIGN.md`: creator experience and canonical world API + +**Current phase:** roadmap proposal. Do not claim tools such as `tools/test.sh` or `tools/validation/run.py` exist until R0 implements and verifies them. diff --git a/COPYING b/COPYING new file mode 100644 index 00000000..9efa6fbc --- /dev/null +++ b/COPYING @@ -0,0 +1,338 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + + 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 Lesser 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. + + GNU GENERAL PUBLIC LICENSE + 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. + + + Copyright (C) + + 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, see . + +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) year 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. + + , 1 April 1989 + Moe Ghoul, 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 Lesser General +Public License instead of this License. diff --git a/README.rst b/README.rst index a161f91b..a49a3d70 100644 --- a/README.rst +++ b/README.rst @@ -1,218 +1,107 @@ -Wolfenstein 3D -============== +Wolf3D Revive +============= -The original source release was made using the ``DEICE.EXE`` -installer (DeIce) in the root directory. (Basically a way to -split self-extracting zip files over multiple floppy disks.) -After execution, that installer will create the contents of -the ``WOLFSRC`` directory. In the "installed" directory, the -the ``README.TXT``, ``RELEASE.TXT``, and ``LICENCE.DOC`` reside -in the ``README`` directory. They are duplicated below. +**A faithful, modern C11 port of the original Wolfenstein 3D for Windows and +Linux, built with SDL3 and CART.** -Travis "Ash" Bradshaw +Wolf3D Revive aims to preserve the original game's look, timing and behaviour, +while making it comfortable to play on modern systems. It is a preservation- +focused source port, **not** a remake or a new game engine. -February 6, 2012 - -RELEASE.TXT ------------ - -:: - - We are releasing this code for the entertainment of the - user community. We don't guarentee that anything even - builds in here. Projects just seem to rot when you leave - them alone for long periods of time. - - This is all the source we have relating to the original - PC wolfenstein 3D project. We haven't looked at this - stuff in years, and I would probably be horribly embarassed - to dig through my old code, so please don't ask any questions - about it. The original project was built in borland c++ 3.0. - I think some minor changes were required for later versions. - - You will need the data from a released version of wolf or spear - to use the exe built from this code. You can just use a - shareware version if you are really cheap. - - - Some coding comments in retrospect: - - The ray casting refresh architecture is still reasonably - appropriate for the game. A BSP based texture mapper could - go faster, but ray casting was a lot simpler to do at the time. - - The dynamically compiled scaling routines are now a Bad Thing. - On uncached machines (the original target) they are the fastest - possible way to scale walls, but on modern processors you just - wind up thrashing the code cash and wrecking performance. - A simple looping texture mapper would be faster on 486+ machines. - - The whole page manager caching scheme is unecessarily complex. - - Way too many #ifdefs in the code! - - - Some project ideas with this code: - - Add new monsters or weapons. - - Add taller walls and vertical motion. This should only be - done if the texture mapper is rewritten. - - Convert to a 32 bit compiler. This would be a fair amount - of work, but I would hate to even mess with crusty old 16 - bit code. The code would get a LOT smaller. - - Make a multi-player game that runs on DOOM sersetup / ipxsetup drivers. - - - Have fun... - - John Carmack - Technical Director - Id Software - -README.TXT +What works ---------- -NOTES: - -This version will compile under BORLAND C++ 3.0/3.1 and compiled perfectly -before it was uploaded. - -Please do not send your questions to id Software. - -LICENCE.DOC ------------ - - :: - LIMITED USE SOFTWARE LICENSE AGREEMENT - - This Limited Use Software License Agreement (the "Agreement") - is a legal agreement between you, the end-user, and Id Software, Inc. - ("ID"). By continuing the downloading of this Wolfenstein 3D - (the "Trademark") software material, which includes source code - (the "Source Code"), artwork data, music and software tools - (collectively, the "Software"), you are agreeing to be bound by the - terms of this Agreement. If you do not agree to the terms of this - Agreement, promptly destroy the Software you may have downloaded. - - ID SOFTWARE LICENSE - - Grant of License. ID grants to you the right to use one (1) - copy of the Software on a single computer. You have no ownership or - proprietary rights in or to the Software, or the Trademark. For purposes - of this section, "use" means loading the Software into RAM, as well as - installation on a hard disk or other storage device. The Software, - together with any archive copy thereof, shall be destroyed when no longer - used in accordance with this Agreement, or when the right to use the - Software is terminated. You agree that the Software will not be shipped, - transferred or exported into any country in violation of the U.S. - Export Administration Act (or any other law governing such matters) and - that you will not utilize, in any other manner, the Software in violation - of any applicable law. - - Permitted Uses. For educational purposes only, you, the end-user, - may use portions of the Source Code, such as particular routines, to - develop your own software, but may not duplicate the Source Code, except - as noted in paragraph 4. The limited right referenced in the preceding - sentence is hereinafter referred to as "Educational Use." By so exercising - the Educational Use right you shall not obtain any ownership, copyright, - proprietary or other interest in or to the Source Code, or any portion of - the Source Code. You may dispose of your own software in your sole - discretion. With the exception of the Educational Use right, you may not - otherwise use the Software, or an portion of the Software, which includes - the Source Code, for commercial gain. - - Prohibited Uses: Under no circumstances shall you, the end-user, - be permitted, allowed or authorized to commercially exploit the Software. - Neither you nor anyone at your direction shall do any of the following acts - with regard to the Software, or any portion thereof: - - Rent; - - Sell; - - Lease; - - Offer on a pay-per-play basis; - - Distribute for money or any other consideration; or - - In any other manner and through any medium whatsoever commercially - exploit or use for any commercial purpose. - - Notwithstanding the foregoing prohibitions, you may commercially exploit the - software you develop by exercising the Educational Use right, referenced in - paragraph 2. hereinabove. - - Copyright. The Software and all copyrights related thereto - (including all characters and other images generated by the Software - or depicted in the Software) are owned by ID and is protected by - United States copyright laws and international treaty provisions. - Id shall retain exclusive ownership and copyright in and to the Software - and all portions of the Software and you shall have no ownership or other - proprietary interest in such materials. You must treat the Software like - any other copyrighted material, except that you may either (a) make one - copy of the Software solely for back-up or archival purposes, or (b) - transfer the Software to a single hard disk provided you keep the original - solely for back-up or archival purposes. You may not otherwise reproduce, - copy or disclose to others, in whole or in any part, the Software. You - may not copy the written materials accompanying the Software. You agree - to use your best efforts to see that any user of the Software licensed - hereunder complies with this Agreement. - - NO WARRANTIES. ID DISCLAIMS ALL WARRANTIES, BOTH EXPRESS IMPLIED, - INCLUDING BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE WITH RESPECT TO THE SOFTWARE. THIS LIMITED - WARRANTY GIVES YOU SPECIFIC LEGAL RIGHTS. YOU MAY HAVE OTHER RIGHTS WHICH - VARY FROM JURISDICTION TO JURISDICTION. ID DOES NOT WARRANT THAT THE - OPERATION OF THE SOFTWARE WILL BE UNINTERRUPTED, ERROR FREE OR MEET YOUR - SPECIFIC REQUIREMENTS. THE WARRANTY SET FORTH ABOVE IS IN LIEU OF ALL OTHER - EXPRESS WARRANTIES WHETHER ORAL OR WRITTEN. THE AGENTS, EMPLOYEES, - DISTRIBUTORS, AND DEALERS OF ID ARE NOT AUTHORIZED TO MAKE MODIFICATIONS TO - THIS WARRANTY, OR ADDITIONAL WARRANTIES ON BEHALF OF ID. - - Exclusive Remedies. The Software is being offered to you free of any - charge. You agree that you have no remedy against ID, its affiliates, - contractors, suppliers, and agents for loss or damage caused by any defect - or failure in the Software regardless of the form of action, whether in - contract, tort, includinegligence, strict liability or otherwise, with - regard to the Software. This Agreement shall be construed in accordance - with and governed by the laws of the State of Texas. Copyright and other - proprietary matters will be governed by United States laws and international - treaties. IN ANY CASE, ID SHALL NOT BE LIABLE FOR LOSS OF DATA, LOSS OF - PROFITS, LOST SAVINGS, SPECIAL, INCIDENTAL, CONSEQUENTIAL, INDIRECT OR OTHER - SIMILAR DAMAGES ARISING FROM BREACH OF WARRANTY, BREACH OF CONTRACT, - NEGLIGENCE, OR OTHER LEGAL THEORY EVEN IF ID OR ITS AGENT HAS BEEN ADVISED - OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so the above limitation or exclusion may not apply to - you. - - General Provisions. Neither this Agreement nor any part or portion - hereof shall be assigned, sublicensed or otherwise transferred by you. - Should any provision of this Agreement be held to be void, invalid, - unenforceable or illegal by a court, the validity and enforceability of the - other provisions shall not be affected thereby. If any provision is - determined to be unenforceable, you agree to a modification of such - provision to provide for enforcement of the provision's intent, to the - extent permitted by applicable law. Failure of a party to enforce any - provision of this Agreement shall not constitute or be construed as a - waiver of such provision or of the right to enforce such provision. If - you fail to comply with any terms of this Agreement, YOUR LICENSE IS - AUTOMATICALLY TERMINATED and you agree to the issuance of an injunction - against you in favor of Id. You agree that Id shall not have to post - bond or other security to obtain an injunction against you to prohibit - you from violating Id's rights. - - YOU ACKNOWLEDGE THAT YOU HAVE READ THIS AGREEMENT, THAT YOU - UNDERSTAND THIS AGREEMENT, AND UNDERSTAND THAT BY CONTINUING THE - DOWNLOADING OF THE SOFTWARE, YOU AGREE TO BE BOUND BY THIS AGREEMENT'S - TERMS AND CONDITIONS. YOU FURTHER AGREE THAT, EXCEPT FOR WRITTEN SEPARATE - AGREEMENTS BETWEEN ID AND YOU, THIS AGREEMENT IS A COMPLETE AND EXCLUSIVE - STATEMENT OF THE RIGHTS AND LIABILITIES OF THE PARTIES. THIS AGREEMENT - SUPERSEDES ALL PRIOR ORAL AGREEMENTS, PROPOSALS OR UNDERSTANDINGS, AND - ANY OTHER COMMUNICATIONS BETWEEN ID AND YOU RELATING TO THE SUBJECT MATTER - OF THIS AGREEMENT - +* The original six-episode campaign systems: enemies, bosses, weapons, pickups, + doors, secrets, intermissions and endings. +* Original-style AdLib music, sound effects and digitised audio read from game + archives, without converting the soundtrack. +* Classic keyboard controls or optional modern WASD and mouse controls. +* Six named save slots, configurable key bindings and persistent settings. +* Original 320x200 presentation with correct 4:3 display proportions, view + sizes, HUD and palette. +* Optional high-resolution software rendering, expanded widescreen views, + fullscreen, display scaling, VSync and screenshots. +* Optional **Smooth Rendering**: interpolated presentation at the display's + refresh rate while keeping the original **70 Hz game simulation**. + +The original renderer remains the default. High-resolution rendering is an +optional presentation mode, not a different game. The active main branch +supports automatic high-resolution render targets up to 4096x2160; further +4K performance work is being developed separately. + +Getting started +--------------- + +You must provide your own legally obtained **Wolfenstein 3D WL6 game data**. +The repository does not distribute commercial game assets. A Steam installation +is one possible data source. + +The project uses CART and SDL3. Once your local CART/SDL3 environment is set up, +a typical Linux build and launch is:: + + ./build/tools/cart build --profile cart-sdl --verbose + ./build/tools/cart run --profile cart-sdl -- --data "/absolute/path/to/WL6" + +The ``cart-sdl`` profile expects the SDL3 SDK in the sibling CART checkout. +There is no automatic game-data download. For Windows builds, alternative SDK +layouts and troubleshooting, see `Build instructions `_. + +Controls +-------- + +Classic controls are the default: arrow keys move/turn, Ctrl fires, Space +operates doors, Shift runs, and number keys select weapons. Select **Modern** +in the Control menu for WASD movement and mouse aiming. + +Useful shortcuts: + +* **Alt+Enter:** toggle fullscreen. +* **F11:** toggle integer display scaling. +* **F12:** save a BMP screenshot. +* **Escape:** open the in-game menu or pause. + +Controls, audio, display choices and view settings are configurable in-game. +The configuration and save files live in the platform's SDL user-data directory. + +Fidelity and project scope +-------------------------- + +The project retains the original DOS source in ``WOLFSRC/`` without modifying +it. The maintained port lives in ``src/``. + +All 60 original maps have been exercised in automated load/render/simulation +coverage at four difficulties. The four attract-mode demos match an instrumented +DOS reference under documented test settings. These results **do not** claim +that full human-played episode runs or every audio/device combination have +been verified. + +The goal is to preserve gameplay and DOS compatibility while improving the +platform and presentation layers. Modding frameworks, replacement art and +major gameplay redesigns are outside the current scope. + +Documentation +------------- + +* `Build, run and controls `_ +* `Milestone 8: frame pacing and benchmarks `_ +* `Milestone 7: widescreen and high-resolution rendering `_ +* `DOS demo synchronization `_ +* `Classic fidelity audit `_ +* `DOS state-transition inventory `_ +* `Milestone 13: final audit and release validation `_ +* `Configuration details `_ +* `Porting notes and progress `_ +* `Licensing and data ownership `_ +* `Historical source-release README `_ + +License and attribution +----------------------- + +The active port's new C engine code is licensed under **GPL-2.0-only**; see +`COPYING `_ and `docs/LICENSING.md `_ for +provenance, third-party notices and the distinction between engine source +and copyrighted game data. Original game assets and trademarks remain their +respective owners' property. + +This project is an independent preservation effort, not an official id Software +release. diff --git a/cart.toml b/cart.toml new file mode 100644 index 00000000..4e6ac985 --- /dev/null +++ b/cart.toml @@ -0,0 +1,44 @@ +# Original-engine UI and E1M1 sprites, actors, movement and combat. +[project] +name = "wolf3d-revive" +version = "0.1.0" +src = "src" +out = "build" + +[linux] +compiler = "gcc" +standard = "c11" +cflags = ["-O2", "-Wall", "-Wextra", "-Wpedantic", "-Wconversion", "-Wshadow"] +defines = [] +include_dirs = ["src"] +lib_dirs = [] +libs = ["m"] + +# GCC/MinGW is explicit because cflags use GCC syntax. MSVC needs its own flags. +[windows] +compiler = "gcc" +standard = "c11" +cflags = ["-O2", "-Wall", "-Wextra", "-Wpedantic", "-Wconversion", "-Wshadow"] +defines = [] +include_dirs = ["src"] +lib_dirs = [] +libs = ["m"] + +[graphics] +backend = "sdl-renderer" + +[deps.sdl3] +enabled = true +path = "vendor/SDL" +linkage = "shared" + +# Optional reuse of the existing sibling CART development dependency. +# Default builds use your own SDL3 SDK at vendor/SDL; this profile downloads nothing. +[profile.cart-sdl.deps.sdl3] +path = "../cart/vendor/SDL" +linkage = "static" + +# SDL's local static build reports -pthread -lm in sdl3.pc. +# CART supplies -lm; this supplies the POSIX threading dependency. +[profile.cart-sdl.linux] +libs = ["pthread"] diff --git a/docs/BUILD.md b/docs/BUILD.md new file mode 100644 index 00000000..c53b6460 --- /dev/null +++ b/docs/BUILD.md @@ -0,0 +1,338 @@ +# Build and run Wolf3D Revive + +CART builds original menus and normal-level gameplay: sprites, enemies, +weapons, pickups, HUD, life restarts, episode/difficulty selection, pushwalls, +elevator exits, intermissions and progression. All original bosses, +projectiles and six finale paths are implemented; all 60 maps load/render/ +simulate at all four difficulties. Native AdLib music and digitised/AdLib effects +play through SDL3. Six named save slots, pause/resume and animated intermissions +are implemented; see [save format and validation](MILESTONE6C.md). See [audio support and limits](MILESTONE6B.md) and +[milestone 6A](MILESTONE6A.md) for verified scope and playthrough limitations. + +## Local Linux build + +From the repository root, reuse the existing SDL3 SDK in the sibling CART checkout: + +```sh +./build/tools/cart build --profile cart-sdl --verbose +./build/tools/cart run --profile cart-sdl -- \ + --data "$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" +``` + +Press any key during the title/credits/scores to open the menu. Use Up/Down +and Enter/Space; V, B and Q select View Scores, Back to Demo and Quit. Escape +opens quit confirmation in the menu (Y exits, N/Escape cancels). Closing the +window exits directly. New Game opens the episode and difficulty pages; arrows select, Enter/Space +confirm and Escape goes back. Sound opens functional Music/Effects enable +switches and independent volumes: Up/Down select, Enter/Space toggles a switch, +Left/Right changes volume in 5% steps. Settings persist on normal exit. Control opens Classic/Modern presets, mouse +enable, sensitivity/invert, reset and two-key action bindings. On the binding +page, arrows select action/alternative, Enter captures a key, Delete unbinds +and Escape cancels. Conflicts retain the old assignment. Changing presets +retains each profile's custom bindings and mouse options; Reset Defaults resets +only the selected profile. Other +unported main-menu rows stay disabled. A failed +level load reports the reason and returns to the menu after acknowledgement. + +In the level: Up/Down move, Left/Right turn, Alt+Left/Right strafe, Shift runs, +Space operates doors, secret pushwalls and elevator switches. Ctrl fires, and +1–4 select owned weapons (knife, pistol, machine gun, chaingun). Keys unlock +their matching doors. Intermissions count the original ratios/time bonus with +original sounds and BJ breathing. A key skips counting; a separate key continues. +Escape during living gameplay pauses and opens the menu. Save Game and Load Game +use six slots: arrows select, Enter confirms, letters/digits/Space edit names, +Backspace deletes and Escape cancels. Y/N confirms replacement, including corrupt +saves. Back to Game resumes the paused simulation. Saving is unavailable during +death, intermissions and victory cinematics. Victory statistics acknowledge with a key; ending articles +use arrows, Enter or Page Up/Down for pages and Escape to close, followed by +scores and return to menu. `--level` starts E1M1 at medium difficulty directly. + +Classic is the default, with the original keyboard controls above. To use WASD +and mouse, open Control and select Modern. W/S move, A/D strafe, mouse X turns, +left-click fires and right-click opens/uses; arrows, Ctrl, Space, Shift and 1–4 +remain available. Mouse capture starts after gameplay fade-in and releases for +menus and focus loss. Sensitivity 1–40 sets 0.05–2 degrees/count (default 10, +0.5 degrees/count). Gameplay bindings do not change menu navigation. These +settings persist across normal restarts and remain current when loading a +save. See [Milestone 6D](MILESTONE6D.md) for input timing and validation details. + +Change View in the main or paused menu changes the actual 3D viewport through +the original sizes 4–19 (64×32 through 304×152; default 240×120). Arrows preview, +Enter accepts and Escape cancels. The original teal border and 40-pixel HUD stay +around the view. This is independent of SDL window or presentation size. + +Control → Display settings selects fullscreen, integer scaling and +window sizes from 320×240 through 1600×1200 (1×–5×). Up/Down selects a row; +Left/Right or Enter changes a setting. Reset Defaults restores a 960×720 +window with fit scaling. Settings persist across normal restarts, including custom window sizes, and +remain current across loads. +Alt+Enter (including keypad Enter) switches borderless desktop fullscreen; +F11 switches integer scaling. These shortcuts are consumed before gameplay +or menu input; F1–F11 cannot be assigned to gameplay actions. Fullscreen changes +clear pending input, so release and press held controls again afterwards. + +The unchanged 320×200 framebuffer fills a 320×240 logical canvas for the +original 4:3 proportions. Fit mode maximizes that canvas with black borders; +integer mode uses whole multiples of the corrected canvas. Below 320×240 +drawable pixels, integer mode temporarily uses fit to avoid cropping. Windows +can be resized freely and restore their previous windowed size after fullscreen. +Size presets use window points; presentation uses drawable pixels on high-DPI +systems. Mouse capture releases during pending mode changes and returns only +for focused gameplay. See [Milestone 6E](MILESTONE6E.md) for calculations, +failure recovery and verification limits. + +During living gameplay, F2 Save, F3 Load, F4 Sound, F5 Change View and F6 +Control return directly to the paused game. F1 is the original GOODTIMES boss +key: a black C> screen, Escape to return. F7 confirms End Game; F8 selects a +quick slot on first use then saves directly; F9 selects a quick slot on first +use then confirms quickload; F10 confirms Quit. These features keep six native +save slots and the existing save format. View/control/display settings remain +current when loading. + +After title, credits and scores, attract mode plays available T_DEMO0–3 streams +from the original graphics archive. A key or click aborts. Missing/corrupt demos +are skipped safely. All four tested owned recordings now match the instrumented +DOS reference at view size 15 with DOS sound off, through their exact durations. +See [Milestone 6G](MILESTONE6G.md) for private reference builds, frame tracing, +source identities and verification limits. Run the added regressions with +`WOLF3D_DATA=/path/to/WL6 python3 -m unittest discover -s tests -p test_demo_sync.py -v`. + +`--no-audio` skips sound loading/device output. Otherwise music and sounds read +AUDIOHED/AUDIOT/VSWAP directly; nothing is converted or written to disk. Audio +startup/device errors report a reason and allow silent gameplay. The logical +original digitised mode (including its 140-tic boss death delays) is identical +with audio muted or disabled. No PC speaker mode is offered. + +An ALSA-only SDL SDK can use `SDL_AUDIO_ALSA_DEFAULT_PLAYBACK_DEVICE=pulse` on +a PulseAudio/PipeWire desktop. The backend tries this endpoint automatically +if ALSA's default fails and no explicit device hint exists. This does not change +ALSA configuration. A full SDL SDK with native PulseAudio/PipeWire support +uses its own default routing. + +Saves use `SDL_GetPrefPath(NULL,"wolf3d-revive")`: normally +`~/.local/share/wolf3d-revive/` on Linux (respecting `XDG_DATA_HOME`) and +`%APPDATA%\wolf3d-revive\` on Windows. Files are `slot1.w3s` through +`slot6.w3s`; back up that directory to preserve games. Original DOS saves are +not compatible. Save errors leave the active game and previous slot intact. +Descriptions use the original ASCII font and a 121-pixel / 31-character limit. + +The discovered Steam directory above is used read-only. Supply a different absolute path if your installation +is elsewhere; `cart run` changes the working directory to the output folder. +No path is hardcoded into the executable and no game data is staged by CART. + +`build/tools/cart` is the ignored current CART 0.2.0 executable produced during +milestone 1. If absent, build the current CART source in `../cart` and use that +executable instead. The installed `cart`/historical tracked binary reported +0.1.0 during milestone 1. No installed tool was overwritten in this milestone. +The local SDL SDK reports development version 3.5.0, revision `08b9c5539`. + +To decode/check without a display, or perform a finite graphical smoke test: + +```sh +./build/cart-sdl/linux/wolf3d-revive --data /absolute/path/to/WL6 --check-assets +./build/cart-sdl/linux/wolf3d-revive --data /absolute/path/to/WL6 --check-ui +./build/cart-sdl/linux/wolf3d-revive --data /absolute/path/to/WL6 --check-level +./build/cart-sdl/linux/wolf3d-revive --data /absolute/path/to/WL6 --level +./build/cart-sdl/linux/wolf3d-revive --data /absolute/path/to/WL6 --menu +./build/cart-sdl/linux/wolf3d-revive --data /absolute/path/to/WL6 --frames 3 +./build/cart-sdl/linux/wolf3d-revive --help +``` + +`--capture build/checks/title.bmp` additionally saves a local SDL readback +of the initial title, menu (`--menu`) or level (`--level`) at full brightness, before +its fade-in (create the parent directory first). SDL readback contains +the image viewport, excluding letterbox bars. Captures contain game artwork; +keep them private and out of Git. `build/`, `*.bmp` and `*.ppm` are ignored. + +## Other SDL SDKs and Windows + +The base config uses ignored `vendor/SDL` with shared linkage. Without that SDK, +base `cart doctor`/`cart build` intentionally reports a missing dependency. +The optional `cart-sdl` profile overrides the root to `../cart/vendor/SDL` and +uses its existing static build; nothing is downloaded or installed. + +Implemented `[deps.sdl3]` keys are `path`, `include_dir`, `lib_dir`, `lib` and +`linkage` (plus `enabled`). Defaults use `include/SDL3` and `build/`, with +fallbacks `build/Release`, `build/Debug`, `build/lib`. Adjust to your SDK layout. +The local profile supplies pthread; CART supplies SDL3 and libm. Other static +SDKs may require additional platform libraries in `libs`. + +The Windows target explicitly selects GCC/MinGW so the warning flags match. +Use a Windows SDL SDK/import library, not the Linux `cart-sdl` profile. Put the +matching SDL3 DLL beside the executable or on PATH. All application C modules pass strict MinGW C11 compilation. A manual cross-link with +the official SDL3 3.4.18 MinGW SDK and a five-frame E1M1 smoke test under Wine +with dummy video/audio passed. Milestone 6C verifies Windows save/overwrite/cancel, UTF-8 save paths and +restart/load under Wine; see [MILESTONE6C.md](MILESTONE6C.md). Milestone 6D +cross-links all 40 C units and passes the Windows controls harness under Wine; +see [MILESTONE6D.md](MILESTONE6D.md). Milestone 6E cross-links all 41 C units +and passes the Windows display geometry/gameplay harness under Wine with +dummy drivers; see [MILESTONE6E.md](MILESTONE6E.md). Classic restoration builds +all 43 C units and passes synthetic/owned viewport, shortcut and demo tests +under Wine; see [CLASSIC_FIDELITY_RESTORATION.md](CLASSIC_FIDELITY_RESTORATION.md). +This is not native Windows verification; +physical Windows playback, device changes and resize behaviour still need +Windows testing. See [MILESTONE6B.md](MILESTONE6B.md). No CMake build system was introduced. + +No CART source changes were required in milestones 2–6. The Linux/Windows +link lists now include the math library used by the original table builder. +CART recursively builds the lowercase +`.c` files under `src`, supporting C11, defines/includes and library lists. +It has no general linker-flags key, pkg-config integration, automatic SDK +build/download, DLL staging or rpath setup. `doctor` does not accept profiles. +Sanitizer flags only reach compilation via `cflags`; use the explicit combined +compile/link below for sanitizers. The prior generic output-directory fix and +its tests in CART remain as they were at the start of this milestone. + +## Tests + +Build the application with CART first, then run the synthetic/unit suite and +existing Git-protection tests: + +```sh +python3 -m unittest discover -s tests -v +``` + +This compiles memory, Huffman, graphics/UI, input, timing, map/VSWAP, raycasting +movement, sprites, RNG, enemy AI, combat, pickups, HUD, death, campaign, +intermission and pushwall tests with GCC C11 and strict warnings as errors. SDL readback +and event-to-menu/game tests use the static SDK at `../cart/vendor/SDL` (override with `SDL_SDK`). The SDL tests use the dummy +video/software renderer, requiring no desktop. Without that static SDK, those +SDL integration tests report skips. Synthetic archives are generated in temporary +directories and removed; no asset fixtures come from commercial files. + +For an independent pixel-by-pixel oracle comparison using your owned files: + +```sh +WOLF3D_DATA="$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" \ + python3 -m unittest discover -s tests -v +``` + +Optional Linux sanitizer build (normal builds remain CART-driven): + +```sh +mkdir -p build/checks +gcc -std=c11 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -fsanitize=address,undefined -fno-omit-frame-pointer -g \ + -Isrc -I../cart/vendor/SDL/include \ + src/main.c src/engine/*.c src/platform/*.c \ + ../cart/vendor/SDL/build/libSDL3.a -pthread -lm \ + -o build/checks/wolf3d-revive-sanitize +SANITIZE=1 UBSAN_OPTIONS=halt_on_error=1 WOLF3D_BINARY="$PWD/build/checks/wolf3d-revive-sanitize" \ + WOLF3D_DATA="$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" \ + python3 -m unittest discover -s tests -v +``` + +`SANITIZE=1` also instruments the C unit/video tests. The reused SDL static +archive is not instrumented. The gameplay simulation and palette flashes use +fixed 70 Hz tics. The campaign suite exercises selection, exits, statistics, +secret routing, pushwalls and later-floor restarts. Audio regressions add bounded archive/sample decoding, deterministic IMF and +shared OPL scheduling, all original music loop durations, volume/priority/position, +RNG independence, both boss delay modes and repeated SDL dummy lifecycle. Finale +SDL tests also initialise sound. Save tests cover all six slots, process restart, +portable CRC/field decoding, corrupt inputs, source identity, failed/competing +writes, deterministic actor/door/pushwall/projectile/boss continuation, audio +restoration and SDL menu input. Controls regressions add Classic/Modern input, +diagonal bounds, mouse sensitivity/buttons/capture, focus transitions, binding +conflicts, settings and save/RNG equivalence. See [Milestone 6C](MILESTONE6C.md). +Display regressions add full-output black-bar readback, integer/fit geometry, +tiny windows, drawable dimensions, external/fullscreen state changes, shortcut +consumption, injected SDL failures, capture/focus and display-independent saves. + +From CART, regression checks can use the current executable by absolute path: + +```sh +CART=/absolute/path/to/wolf3d-revive/build/tools/cart sh tests/test_sdl3.sh +CART=/absolute/path/to/wolf3d-revive/build/tools/cart sh tests/test_desktop_dirs.sh +``` + +See [milestone 6 results and scope](MILESTONE6.md) for validation and remaining work. + +Classic regression coverage and DOS comparison limits are recorded in +[CLASSIC_FIDELITY_RESTORATION.md](CLASSIC_FIDELITY_RESTORATION.md). + +Preferences use `SDL_GetPrefPath(NULL,"wolf3d-revive")/config.toml`, beside but +separate from save slots: `$XDG_DATA_HOME/wolf3d-revive/` or normally +`~/.local/share/wolf3d-revive/` on Linux, `%APPDATA%\wolf3d-revive\` on Windows. +See [MILESTONE6F.md](MILESTONE6F.md) for the actual schema/defaults, two preset +profiles, fixed TOML subset, atomic writes and verified limitations. Malformed, +unreadable or future-version files are preserved; fix or rename them to restore +normal-exit preference saving. Check-only commands do not touch configuration. +The configuration tests use Python 3.11+ for the independent standard-library +`tomllib` output check; the native application has no Python dependency. + + +## Native visual settings (Milestones 7–8) + +Control → Display selects Original / High Resolution, fixed or Auto desktop +resolution, Auto / 4:3 / 16:9 / 16:10 / 21:9 / 32:9 aspect, VSync, Integer / Fit +and Nearest / Linear presentation filtering. Smooth Rendering enables +read-only interpolation in High Resolution and automatically follows the active +display's refresh, with a 60 FPS fallback and 240 FPS ceiling. There is no +manual FPS selection. Original remains the default. +Alt+Enter and F11 retain their existing functions; F12 writes a BMP in the +SDL preference directory. No image or game-data files belong in the repository. + +The existing CART command builds the native renderer with C11/SDL3 and libm: + +```sh +./build/tools/cart build --profile cart-sdl +WOLF3D_DATA="/path/to/owned/WL6" python3 -m unittest discover -s tests -v +SANITIZE=1 UBSAN_OPTIONS=halt_on_error=1 WOLF3D_DATA="/path/to/owned/WL6" \ + python3 -m unittest discover -s tests -v +``` + +`test_render.py` covers target boundaries, aspect helpers, native geometry, +Original hashes, HUD composition, SDL switching, preference restoration, +screenshots and audio render stalls. `test_demo_sync.py` additionally renders +widescreen during all four DOS-reference recordings. Test harnesses compile +with `-Werror` as well as strict C11 conversion/shadow/pedantic warnings. +See [MILESTONE7_VISUAL.md](MILESTONE7_VISUAL.md) for schema, measurements, +Windows/Wine checks and verification limits. Sanitizer application tests should +set `WOLF3D_BINARY` to a separately built sanitized full executable. + +See [MILESTONE8.md](MILESTONE8.md) for fixed-step debt semantics, VSync pacing, +interpolation boundary tests, end-to-end benchmarking commands and measured +performance/hardware limitations. `test_presentation.py` verifies immutable +snapshots and identical simulation saves across all eight requested rates. + +## Milestone 12 DOS interaction + +Pause displays the original pause picture during living gameplay; a fresh key +or click resumes. Pause in menus toggles music. New Game confirms replacing an +active game after episode selection. Quit uses all nine original sayings. +When mouse input is enabled, relative menu movements over 60 counts navigate, +left-click accepts and right-click cancels; Y/N confirmations use the keyboard. + +Final death and episode endings qualify the score by points, then floor reached. +Enter saves the typed name; Escape leaves it blank while keeping the score. +Scores persist separately as `highscores.w3h` in the SDL preference directory. +Invalid/future score files are preserved; session rankings still work. + +Hold M during startup, press M at sign-on, or use `--jukebox` for Robert's +Jukebox. M+L+I grants the original inventory while zeroing score and adding ten +minutes; B+A+T displays the Keen Easter egg. `--goobers` permits the original +Backspace+LeftShift+Alt debug unlock, followed by Tab+G/H/I/E/F/C/P/Q/W/X. +See [the fidelity checklist](MILESTONE12_DOS_FIDELITY_BACKLOG.md) for exact +supported scope, intentional native systems and outstanding comparisons. + +## Transition inventory (Milestone 13) + +The source/evidence audit needs only Python and the checkout, without game data: + +```sh +python3 scripts/audit_transitions.py --check +python3 -O scripts/audit_transitions.py --check +``` + +After reviewing a source/transition change, update +`docs/dos_state_transitions.json`, then regenerate the review document with +`python3 scripts/audit_transitions.py --write`. Missing/stale/invalid inventory +files fail the check and the standard unittest suite. This check validates +traceability and route coverage, not runtime DOS equivalence. Current executed +DOS and release results are in [Milestone 13](MILESTONE13_FINAL_FIDELITY.md). + +Menu mouse navigation keeps the DOS movement threshold and gun cursor. With +mouse input enabled, menus use relative capture to hide the desktop pointer +and avoid stopping at a screen edge. Focus loss, pending display changes, +disabling mouse input and shutdown release capture. Keyboard navigation remains +available; mouse movement in a menu never becomes gameplay movement or firing. diff --git a/docs/CLASSIC_FIDELITY_AUDIT.md b/docs/CLASSIC_FIDELITY_AUDIT.md new file mode 100644 index 00000000..1286477f --- /dev/null +++ b/docs/CLASSIC_FIDELITY_AUDIT.md @@ -0,0 +1,96 @@ +# Classic DOS fidelity restoration + +Classic targets the original DOS rules; this branch does **not** claim complete +DOS equivalence. The initial restoration was `feature/classic-fidelity-restoration`, +PR #5. Current completion work is on `feature/12-dos-fidelity-completion`; +see the [Milestone 12 checklist and verification matrix](MILESTONE12_DOS_FIDELITY_BACKLOG.md) +and [initial implementation and verification](CLASSIC_FIDELITY_RESTORATION.md). + +## Restored in this pass + +- Variable-size 3D viewport: all original sizes 4–19, default 15, using + `WL_MAIN.C` NewViewSize/CalcProjection formulas. Rays, wall/sprite scalers, + weapon placement, combat view thresholds and death effects use active sizes. +- Original teal play border and bevel (`WL_GAME.C` DrawPlayBorder), including + safe restoration around the viewport, HUD, menus and save/load. +- DOS Change View preview, arrows, bounds, Enter acceptance and Escape cancel + (`WL_MENU.C` CP_ChangeView). Native SDL display controls are separate, under + Control → Display settings. +- F2 Save, F3 Load, F4 Sound, F5 Change View and F6 Control now return directly + to paused gameplay. The initial branch compiled and passed 70 regressions, + but its F-key panels returned to the main menu and F5 opened SDL settings. +- F1 implements the **GOODTIMES boss key**, matching `VERSION.H` and + `US_ControlPanel`: a native black “C>” screen, paused music/gameplay, Escape + to return. The non-GOODTIMES HelpScreens path is a different release variant. +- F7 End Game confirmation, F8 quicksave/initial slot selection, F9 quickload + confirmation/initial slot selection and F10 Quit confirmation, following + `CP_CheckQuick`. Function keys are reserved from gameplay bindings. +- Original embedded `T_DEMO0`–`T_DEMO3` command playback in the attract cycle, + with bounded archive decoding, fixed RNG seed, signed movement, original + buttons, four-tic updates and key/click abort. Missing/corrupt/unsupported + demos are skipped; the attract loop continues instead of fabricating input. + +## Remaining fidelity differences + +1. **Demo synchronization is verified for the Milestone 6G reference scope.** + All four recordings match every traced frame through their declared durations + at view size 15 with DOS sound off. Other releases/view sizes and enabled-DOS + audio timing need equivalent comparisons. See [MILESTONE6G.md](MILESTONE6G.md) + for the original executable reference, proven corrections and remaining limits. +2. The GOODTIMES boss screen uses the existing game font in the 320×200 SDL + framebuffer, rather than switching hardware to BIOS text mode. Help for + other release layouts is not implemented. The retained owned help article + contains picture references that do not fit this GOODTIMES picture layout; + it is not silently remapped or drawn out of bounds. +3. Milestone 12 restores all nine quit sayings with the original C selection + precedence, confirmation blinking/release/sounds, Pause, new-game refusal, + high-score qualification/editing/persistence and Saving/Loading pictures. + End Game now follows final death into qualification and attract mode. + `WL_GAME.C GameLoop` has **no separate Game Over card** in this edition. + The 20 executed-DOS dialog frames match pixel-for-pixel. Disk-flip timing + follows native operation phases, not DOS serialization chunks; UI entropy + intentionally stays separate from gameplay RNG. +4. Six portable save slots and format version 1 remain; original DOS ten-slot + files are not introduced. Settings, including view size, now persist separately + in [Milestone 6F TOML preferences](MILESTONE6F.md). +5. Full VGA/CRT pixel equivalence is not established. Milestone 6G corrects + actor projection to DOS `centerx=width/2-1` and verifies traced visibility at + the default size. Safe clipping of death-fizzle edge pixels remains. +6. Milestone 12 adds MLI/BAT, Robert's Jukebox, supported portable debug keys, + device-capability sign-on lights, DOS mouse navigation and text editing. + Physical ISA/gameport/EMS/XMS diagnostics and native joystick/gamepad input + remain unsupported. Non-GOODTIMES/SPEAR/localized menus need matching data + and separate verification. Full physical DOS audio/CRT parity remains open. + Classic/Modern are input presets; Enhanced is a presentation/renderer mode, + sharing the original simulation. No separate gameplay mode was introduced. + +## Protection and verification + +WOLFSRC, master and commercial game files are unchanged. All generated data, +private captures and binaries remain outside tracked source assets. Tests cover +all 16 view sizes, border/HUD/sprite/death clipping, save/RNG isolation, function +keys, pause/return, quick-operation errors, demo headers/cadence/input isolation, +missing/corrupt streams and owned data. Full regression, sanitizer and available +Windows results and hardware limitations are recorded in +[CLASSIC_FIDELITY_RESTORATION.md](CLASSIC_FIDELITY_RESTORATION.md). + +Milestone 12 additionally covers editor repeats, atomic high-score files, +original-DOS dialog pixels under DOSBox, native 1920×1200 aspect readback and +strict Linux/MinGW builds. Current full-suite results and precise remaining +limits are recorded in the linked milestone document. + +Final Milestone 12 validation passed 146 normal and 146 ASan/UBSan tests without +skips or findings, plus the final completion-timing follow-ups. WOLFSRC remains +unchanged; see the milestone matrix for executed-DOS, native display and Wine +results and the physical hardware/edition limitations. + +## Milestone 13 audit and release hardening + +The [current transition inventory](DOS_STATE_TRANSITIONS.md) accounts for all +native UI states and original exit values, with explicit verification gaps. +[Milestone 13](MILESTONE13_FINAL_FIDELITY.md) records the established-quickload +correction, 30 executed-DOS drawing frames, expanded 21:9/32:9 loading checks +and current release validation. The earlier counts above are historical. +Entry palette fading versus DOS `fizzlein`, safe death-fizzle clipping, +enabled-sound face/RNG behavior and physical audio/display comparison remain +explicit differences or open evidence gaps. diff --git a/docs/CLASSIC_FIDELITY_RESTORATION.md b/docs/CLASSIC_FIDELITY_RESTORATION.md new file mode 100644 index 00000000..5a90e68d --- /dev/null +++ b/docs/CLASSIC_FIDELITY_RESTORATION.md @@ -0,0 +1,221 @@ +# Classic fidelity restoration — implementation and tests + +Branch: `feature/classic-fidelity-restoration`, PR #5. Baseline: `42ae8e2`, +based on merged Milestone 6E (`e35bd48`). The initial F2–F6 code was compiled +with CART and checked with the full 70-case owned-data suite before editing: +**70 passed in 303.929 seconds**. A separate strict-C11 SDL harness verified +all five initial panel entry points and frozen game time, and exposed the +incorrect return to the main menu. F5's native display panel was also an +explicit mismatch in the initial audit. + +This pass implements native C11/SDL3 behaviour from the protected DOS source. +No WOLFSRC, commercial archives, save format, original artwork or master +branch is changed. No PR is merged automatically. + +## Variable viewport and border + +`WL_VIEW.c` ports the original NewViewSize and CP_ChangeView workflow: + +- Size `n` is 4 through 19 inclusive; default 15. +- `width = n*16`, `height = n*8` (HEIGHTRATIO 0.50); all heights are even. +- `x = (320-width)/2`, `y = (160-height)/2`; the lower 40 pixels are the HUD. +- The resulting range is 64×32 at (128,64) through 304×152 at (8,4). +- Pixel-angle tables are recalculated for the active width using the existing + DOS focal length/MINDIST formulas. Ray-angle and wall-height buffers have a + bounded 304-column capacity; drawing iterates only over active columns. +- Wall posts, sprite clipping/occlusion, weapon scaling, death fizzle and + death-camera regions use active geometry. The existing fixed-point traversal, + movement/collision and ray hit rules remain in place. This is a real smaller + raycast view, not a scaled copy of the former 240×120 image. + +The original DrawPlayBorder fills the top 160 rows with palette index 127, +clears the view black, and draws black top/left, index-125 bottom/right, and +index-124 lower-left corner bevels. Palette values are not replaced with RGB +approximations. Menu return redraws the border/view/HUD without advancing +actors, pickups or RNG. View size remains current when loading a save and is +not serialized in the existing format. + +Change View previews an empty black view against that border. Left/Down +shrinks, Right/Up enlarges; bounds clamp at 4 and 19. Held arrows repeat every +10 presentation tics without blocking the event loop. Preview does not commit +view geometry; Enter commits and Escape cancels. The three original instruction +lines use the existing Wolfenstein font. Native fullscreen/scaling/window size +settings now live at **Control → Display settings**, retaining Alt+Enter/F11. +Both input presets use the same Classic viewport and menus. + +## Function keys and pause/return + +`WL_MAIN.c` separates a direct F-key panel's return destination from a panel +opened in the main control menu. Direct panels freeze game simulation and +return to it; main-menu panels return to their parent menu. Resume resets the +simulation clock after fade-in, clearing pending input. Loaded games also use +that resume boundary. Death, victory and intermission retain save restrictions. + +| Key | In living gameplay | +| --- | --- | +| F1 | GOODTIMES boss key: black C> prompt; Escape resumes | +| F2 | Save Game; unavailable storage leaves gameplay usable | +| F3 | Load Game; unavailable storage leaves gameplay usable | +| F4 | Sound settings | +| F5 | Original Change View | +| F6 | Control settings; native display is a separate child panel | +| F7 | End Game, with Y/N/Escape confirmation | +| F8 | Quicksave to the selected quick slot; first use opens Save | +| F9 | Confirm quickload; first use opens Load | +| F10 | Quit, with Y/N/Escape confirmation | + +F8 writes the existing description without asking to overwrite an established +quick slot. F9 names the slot before loading. The save menu's last selection +is shared by established quick operations, as in DOS. Canceled initial +selection does not establish a quick slot. Invalid/missing slots reopen normal +selection. Load failures retain the live game and present an acknowledgement; +confirmation-time corruption is tested. New/end game clears quick selection. +The original six portable slots and atomic save implementation are retained. + +F1 deserves special care: `WOLFSRC/VERSION.H` defines GOODTIMES. In that +configuration `US_ControlPanel(sc_F1)` calls BossKey, not HelpScreens. The SDL +implementation stays in the original framebuffer, draws C> with an existing +font, mutes music temporarily and restores the user's music/effects settings +on Escape. It never invokes a shell or DOS emulator. Other release help layouts +are outside the currently supported GOODTIMES layout. No attempt is made to +render the incompatible retained help-article picture references. + +F1–F11 cannot be assigned to gameplay actions. SDL non-repeat key edges enter +the original menu scan-state boundary before simulation. Function-key entry +clears pending action input, so it cannot also fire/move on the entry tic. +Fullscreen shortcuts keep their separate Milestone 6E consumption rules. + +## Attract-mode demos + +The original title (15 s), credits (10 s) and high scores (10 s) now lead to a +validated embedded demo, then back to the title. T_DEMO0 through T_DEMO3 rotate +between cycles; invalid/missing chunks or unavailable maps are skipped safely. +The existing CA Huffman decoder performs all archive reads; data is never +modified or extracted into distributable fixtures. + +`WL_DEMO.c` checks the four-byte header and declared little-endian length, +requires complete three-byte commands, maps in 0–59, and signed movement in +original bounded −100…100 units. The fourth header byte is ignored, as in DOS: +the first two owned streams contain 0xd8 there, not a required zero. It is not +treated as a high length byte. Buttons use original attack/strafe/run/use and +weapon bit positions. Run is already represented in recorded movement values; +those values are not scaled a second time for the run bit. + +Playback starts hard difficulty and RNG index zero. It bypasses live bindings, +mouse turning and Modern movement; recorded use edges and attack/weapon states +feed the original game functions. Commands advance in four-tic groups, matching +DEMOTICS=4, and movement, actor transition/think timers, projectile speed, door/ +pushwall movement, face/attack clocks and palette decay use that group size. +Normal gameplay continues to use one tic per simulation update. Accumulating +one tic at a time or four at a time produces identical demo state/frame hashes. +A long host stall retains the existing bounded catch-up policy; it does not +make gameplay simulation depend on display frame count. + +Playback shows the original SPR_DEMO overlay. Saving and relative mouse capture +are disabled for attract demos. A fresh key or mouse click aborts to the menu; +unfocused clicks are ignored and held clicks are not reused as gameplay fire. +End, death, exit or decoding failure releases demo/game state. Missing/corrupt +streams continue the attract cycle rather than pretending a demo ran. + +**Historical results, superseded by [Milestone 6G](MILESTONE6G.md):** all four +recordings now match the documented DOS reference scope and complete their +recorded duration. The following table records the original restoration result. + +**Original synchronization limitation:** the owned streams are valid but do not complete +their recorded paths in this port. Current measured playback is: + +| Demo | Source map | Declared tics | Tics before death | +| --- | --- | --- | --- | +| 0 | 37 (E4M8) | 2764 | 1048 | +| 1 | 43 (E5M4) | 7596 | 928 | +| 2 | 56 (E6M7) | 4560 | 1532 | +| 3 | 31 (E4M2) | 6624 | 396 | + +These are observed native-port results, not DOS reference results. No immunity, +extra ammunition, replacement commands or modified commercial assets are used +to force completion. Synthetic streams reach their exact declared duration; +owned runs are deterministic across input presets and clock batching. An +instrumented DOS-versus-port trace is still required to locate remaining +simulation/visibility/RNG-order differences. Do not label this complete demo +fidelity. Native episode/floor HUD numbering also normalizes global demo map +indices rather than showing DOS's global “floor 38” style number. + +## Verification + +Final results on 2026-11-02: + +- CART build passes. All 43 application C translation units compile with + strict C11 warnings as errors in Linux sanitizer and MinGW builds. +- Full **78-case regression suite with owned data passes** (331.748 seconds). + This includes all 240 map/difficulty combinations, six controlled finale + paths, original graphics/RNG/AI, sound timing and save/load regressions. +- Full **78-case ASan/UBSan suite passes** (844.700 seconds), with + `UBSAN_OPTIONS=halt_on_error=1` and no sanitizer reports. The final eight + focused Classic cases also pass separately under sanitizers (43.355 seconds), + including the explicit F2-save/F3-load and invalid-episode guard checks. +- A separate comparison compiles the baseline branch's controls harness + against baseline and final source. Complete save payloads in slots 1, 2, 3, + 5 and 6 match byte-for-byte across revisions for both synthetic and owned + data, covering normal Classic/Modern input, enemy/RNG state and save resume. +- CART SDL3 and desktop-output-directory regression scripts pass. +- The final application and Classic harness cross-link against the official + SDL3 3.4.18 MinGW SDK. Under Wine/dummy drivers, all six synthetic/owned + viewport, shortcut and demo cases pass, including full save-payload equality. + Five-frame owned E1M1 application startup passes under Wine and under Linux + ASan/UBSan with isolated user-data storage. These are not physical Windows + keyboard/mouse/display tests. +- A Linux X11/software-renderer shortcut/panel check passes on repeat, and + private owned-data Change View / resized-view captures were visually + inspected. The original-font instructions fit the 320×200 UI and teal border + surrounds the active view and HUD correctly. An earlier desktop attempt + failed while acknowledging a quickload error; it did not reproduce with + diagnostics enabled, and its cause is not established. Deterministic dummy + driver runs pass. This is recorded as a desktop-automation limitation, not + evidence of exhaustive physical-input testing. + +Reproduction commands: + +```sh +./build/tools/cart build --profile cart-sdl +WOLF3D_DATA=/absolute/path/to/owned/WL6 python3 -m unittest discover -s tests -v +``` + +The sanitizer command and SDK configuration are in [BUILD.md](BUILD.md). +The new eight-case `test_classic.py` builds its SDL C harness with strict C11 +warnings as errors, optionally ASan/UBSan. Tests cover synthetic/owned data, +all 16 sizes, DOS projection-angle and border-pixel oracles, oversized wall/ +sprite clipping, untouched HUD rows, every-size death fizzle, full save-payload +isolation, current view on load, F1–F10 dispatch, direct return/frozen clock, +view acceptance/cancel/clamps, storage absence, quicksave/quickload/corruption, +confirmation cancel/accept, malformed/missing demos, exact synthetic durations, +owned replay diagnostics, render hashes, clock cadence and focus/key/click abort. +Existing attract tests now expect another title cycle or a real demo, and display +tests enter native settings through Control rather than Change View. + +Known fidelity differences are tracked in +[CLASSIC_FIDELITY_AUDIT.md](CLASSIC_FIDELITY_AUDIT.md). No physical Windows input, +high-DPI/multi-monitor or physical DOS/VGA parity is claimed. Reused SDL's +static library is not sanitizer-instrumented. Campaign coverage remains all +map/difficulty combinations and controlled finales, not full human playthroughs. + +## Milestone 12 continuation + +The later completion branch restores quit personality, shared confirmations, +Pause, new-game replacement confirmation, high-score entry/persistence, +completion transitions, jukebox, MLI/BAT, portable debugging, sign-on capability +lights, mouse navigation, editor repeats and disk activity artwork. It retains +these viewport/demo protections and the native save/configuration formats. +See [the complete source/verification matrix](MILESTONE12_DOS_FIDELITY_BACKLOG.md). +The actual historical executable now supplies a private 20-frame pixel oracle +for all quit sayings at both DOS dialog heights and Saving/Loading windows. +Hardware diagnostics, other editions and physical audio/CRT comparison remain +explicitly outside the verified result. + +## Milestone 13 continuation + +See [the final audit/hardening report](MILESTONE13_FINAL_FIDELITY.md) and +[complete state-transition inventory](DOS_STATE_TRANSITIONS.md). Established +quickload now resumes directly without Get Psyched, as `CP_LoadGame(1)` does. +The private executed-DOS drawing oracle covers 30 frames, including partial +Get Psyched progress and default scores; continuous presentation parity is +still limited to the explicitly recorded evidence. diff --git a/docs/DOS_STATE_TRANSITIONS.md b/docs/DOS_STATE_TRANSITIONS.md new file mode 100644 index 00000000..ec3afcf4 --- /dev/null +++ b/docs/DOS_STATE_TRANSITIONS.md @@ -0,0 +1,1749 @@ +# DOS interaction and state-transition inventory + +Scope: registered GOODTIMES WL6 historical source and native SDL3 engine. This is a reviewed directed-route inventory, not an exhaustive enumeration of every branch/input combination. +Evidence records distinguish source review, native regression assertions and execution of the checksum-verified original DOS executable. Current run results are in [Milestone 13](MILESTONE13_FINAL_FIDELITY.md). + +## How to read the evidence + +- **source-reviewed**: Source correspondence inspected; no runtime or pixel-equivalence claim. +- **partial**: Known intentional difference or verification gap remains; see linked findings. + +Inventory: **46 phases, 106 directed transition records**, all **28 native UI states** and **10 DOS exit values** accounted for. + +A linked test is evidence only for its stated assertions. It does not prove the complete transition, DOS fade/audio equivalence, or a continuous playthrough. This audit adds no new runtime pass claims. + +## Principal journeys + +```mermaid +flowchart LR + Menu --> Episode --> Difficulty --> Setup --> Psyched --> Reveal --> Gameplay + Gameplay --> DeathTurn --> RedFizzle --> DeathAck + DeathAck --> Restart --> Reveal + DeathAck --> Scores --> Title + Gameplay --> Completion --> Psyched + Gameplay --> SecretCompletion --> Psyched + Gameplay --> BJOrBossReplay --> Victory --> Article --> Scores + Menu --> OrdinaryLoad --> Setup + Gameplay --> QuickLoad --> Gameplay + Menu --> QuitConfirm --> Exit +``` + +The graph describes DOS routes. In particular, death restart bypasses Get Psyched, and established-slot quickload returns to the existing play loop. Differences below remain open. + +- **New game**: title → menu → episode → difficulty → setup → psyched → psyched → reveal → gameplay. Rows: title-menu, menu-episode, episode-difficulty, difficulty-setup, setup-psyched, psyched-progress, psyched-reveal, reveal-game. +- **Death restart**: gameplay → death-turn → red-fizzle → death-ack → restart → gameplay. Rows: death-turn, death-fizzle, death-ack, death-restart, restart-reveal. +- **Final death**: gameplay → death-turn → red-fizzle → death-ack → qualification → name-entry → title. Rows: death-turn, death-fizzle, death-ack, death-final, qualify, name-save. +- **Secret floor**: gameplay → secret-completion → setup → psyched → reveal → gameplay. Rows: secret-completion, secret-entry, setup-psyched, psyched-reveal, reveal-game. +- **Ordinary load**: menu → load → disk → setup → psyched → reveal → gameplay. Rows: menu-load, load-work, ordinary-load-setup, setup-psyched, psyched-reveal, reveal-game. +- **Established quickload**: gameplay → quick-confirm → quick-disk → gameplay. Rows: quickload-confirm, quickload-yes, quick-resume. +- **Victory**: gameplay → boss-replay → victory → article → qualification → results → title. Rows: boss-victory, victory-stats, victory-article, article-scores, not-qualified, results-title. +- **Quit**: menu → quit-confirm → exit. Rows: quit-menu, quit-yes. +- **Startup/attract**: process → signon → rating → title → credits → attract-scores → demo → title. Rows: startup, signon-ack, rating-title, title-credits, credits-scores, scores-demo, demo-title. +- **End Game**: gameplay → end-confirm → death-turn → red-fizzle → death-ack → qualification → results → title. Rows: end-game, end-yes, death-fizzle, death-ack, death-final, not-qualified, results-title. + +## Findings that prevent a DOS-equivalence claim + +### presentation — P1: Continuous executed-DOS comparison incomplete + +30 controlled indexed frames and four sound-off demo state traces do not establish all intermediate fades, gameplay composites, victory/article/name-entry or death frames. + +Source/implementation: [PreloadGraphics](../WOLFSRC/WL_INTER.C#L965); [StepPreloadGraphics](../src/engine/WL_INTER.c#L252) + +Rows: startup, signon-ack, rating-title, title-credits, credits-scores, scores-demo, demo-title, title-menu, credits-menu, attract-scores-menu, demo-menu, menu-episode, episode-difficulty, episode-replace, replace-yes, replace-no, difficulty-setup, episode-back, difficulty-back, setup-psyched, psyched-progress, psyched-reveal, reveal-game, game-pause, pause-game, game-menu, menu-game, save-panel, load-panel, menu-save, menu-load, save-work, load-work, ordinary-load-setup, save-return, save-cancel, load-cancel, quicksave, quickload-confirm, quickload-yes, quickload-no, quick-resume, message-return, death-turn, death-fizzle, death-ack, death-restart, restart-reveal, death-final, exit-completion, secret-completion, next-setup, secret-entry, secret-return, boss-victory, victory-stats, victory-article, article-scores, qualify, not-qualified, name-save, results-title, quit-menu, quit-game, quit-no, quit-yes, panel-sound, return-sound, panel-view, return-view, jukebox, jukebox-return, warp-setup, menu-scores, scores-menu, menu-attract, game-sound, sound-game, game-view, view-game, save-cancel-game, load-cancel-game, quit-no-game, end-game, end-menu, end-yes, end-no, end-no-menu. + +Close with: Capture synchronized original DOS intermediate framebuffer/palette/input/audio records for these journeys. + +### cache — P2: Native cache and I/O cadence + +Native heap residency and bounded reads replace DOS main/EMS/XMS budgets and disk speed; exact page counts and duration differ. + +Source/implementation: [PM_Preload](../WOLFSRC/ID_PM.C#L943); [StepPreloadGraphics](../src/engine/WL_INTER.c#L252) + +Rows: setup-psyched, psyched-progress, psyched-reveal. + +Close with: Treat as intentional adaptation; compare visual progress formula separately from hardware-dependent duration. + +### entry-fizzle — P1: Gameplay-entry reveal differs + +DOS GameLoop sets fizzlein; Revive uses a 30-tic palette fade after loading and redraws immediately on death restart. Neither reproduces DOS ThreeDRefresh/FizzleFade gameplay-entry reveal. This is an acknowledged visual difference, not pixel parity. + +Source/implementation: [GameLoop](../WOLFSRC/WL_GAME.C#L45); [StepPreloadGraphics](../src/engine/WL_INTER.c#L252) + +Rows: psyched-reveal, reveal-game, restart-reveal. + +Close with: Implement and independently compare DOS entry fizzle before claiming complete presentation equivalence. + +### fizzle-clip — P2: Safe red-fizzle clipping + +Revive clips to the active viewport; DOS FizzleFade accepts x==width/y==height and can overdraw border pixels. + +Source/implementation: [FizzleFade](../WOLFSRC/ID_VH.C#L462); [Died](../src/engine/WL_PLAY.c#L81) + +Rows: death-fizzle. + +Close with: Retain safe clipping as an intentional difference unless a bounded compatible renderer is separately demonstrated. + +### storage — P2: Portable storage/error flows + +Six versioned atomic native saves and separate score/config files replace DOS ten-slot formats. Native I/O/error and disk-flip phases differ. + +Source/implementation: [CP_LoadGame](../WOLFSRC/WL_MENU.C#L69); [GameRestoreClock](../src/engine/WL_PLAY.c#L236) + +Rows: save-panel, load-panel, menu-save, menu-load, save-work, load-work, ordinary-load-setup, save-return, save-cancel, load-cancel, quicksave, quickload-confirm, quickload-yes, quick-resume, storage-error, name-save, asset-error, error-menu, save-cancel-game, load-cancel-game, preload-error, save-error. + +Close with: Document compatibility boundary; keep corruption, atomic failure and restart regressions passing. + +### hardware — P2: Portable hardware, input and debug adaptations + +No ISA/gameport/EMS/XMS detection, BIOS text mode, controller calibration or DOS timing/cache debug emulation. Native display/binding panels and startup plumbing differ. + +Source/implementation: [IntroScreen](../WOLFSRC/WL_MENU.C#L2882); [DemoLoopStartupDevices](../src/engine/WL_MAIN.c#L26) + +Rows: startup, quit-yes, panel-controls, return-controls, panel-display, return-display, panel-boss, return-boss, jukebox, debug-warp, cheat-message, game-controls, controls-game, game-boss, boss-game, window-close. + +Close with: Document unsupported hardware/editions and verify actual native devices separately. + +### ui-rng — P2: Separate UI entropy + +Quit-message selection uses separate native UI entropy, preserving gameplay/demo RNG rather than consuming original US_RndT. + +Source/implementation: [CP_Quit](../WOLFSRC/WL_MENU.C#L492); [QuitMessage](../src/engine/WL_MAIN.c#L35) + +Rows: quit-menu, quit-game. + +Close with: Retain intentional separation and test original saying selection precedence independently. + +### audio — P1: Physical FM/PCM balance unverified + +The current wide-accumulator ×4 FM gain, synth and native volume controls are not calibrated against physical OPL/Sound Blaster output. Scheduling/priority tests do not establish loudness parity. DOS UpdateFace skips RNG while GETGATLINGSND is playing; the native engine intentionally retains audio-independent face/RNG updates. The four reference demos use DOS sound off. DOS Died also calls SD_WaitSoundDone after acknowledgement; native death has no separate sound-completion gate. The existing fizzle/wait usually outlasts the effect, but early acknowledgement versus FM completion is not independently verified. + +Source/implementation: [CP_Sound](../WOLFSRC/WL_MENU.C#L67); [BeginSoundSettings](../src/engine/WL_MENU.c#L246) + +Rows: death-ack, panel-sound, return-sound, game-sound, sound-game. + +Close with: Measure representative enabled-DOS tracks/effects against a documented device/reference before changing gain. + +## Transition records + +### Startup + +#### startup: process → signon + +**Trigger:** Initialize subsystems and optional SIGNON.RAW **Status:** `partial`. + +- **DOS source:** [InitGame](../WOLFSRC/WL_MAIN.C#L1138); [IntroScreen](../WOLFSRC/WL_MENU.C#L2882) +- **Timing:** Native initialization; optional sign-on 10-tic fade. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Owned 320×200 sign-on; actual mouse/audio capability lights. +- **Sound/music:** Silent sign-on. +- **Input/state:** Fresh key acknowledges; M enters jukebox. +- **Revive:** [DemoLoopStartupDevices](../src/engine/WL_MAIN.c#L26); [DemoLoopSignon](../src/engine/WL_MAIN.c#L154) +- **Regression evidence:** [signon](#signon). Open findings: hardware, presentation. + +#### signon-ack: signon → rating + +**Trigger:** FinishSignon acknowledgement **Status:** `partial`. + +- **DOS source:** [FinishSignon](../WOLFSRC/WL_MAIN.C#L760); [PG13](../WOLFSRC/WL_INTER.C#L305) +- **Timing:** 30-tic black fade with original gamepal reveal; simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original Working prompt then PG13 at (216,110). +- **Sound/music:** Title music 7 begins on rating/title boundary. +- **Input/state:** Clear acknowledging input. +- **Revive:** [SignonPrompt](../src/engine/WL_MAIN.c#L142); [DemoLoopIntro](../src/engine/WL_MAIN.c#L180) +- **Regression evidence:** [signon](#signon). Open findings: presentation. + +### Attract + +#### rating-title: rating → title + +**Trigger:** Seven seconds or fresh input **Status:** `partial`. + +- **DOS source:** [PG13](../WOLFSRC/WL_INTER.C#L305); [DemoLoop](../WOLFSRC/WL_MAIN.C#L1404) +- **Timing:** 7×70-tic hold, 30-tic black fade. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** PG13 to TITLEPIC. +- **Sound/music:** Track 7. +- **Input/state:** Fresh input skips rating. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [signon](#signon). Open findings: presentation. + +#### title-credits: title → credits + +**Trigger:** Attract deadline **Status:** `partial`. + +- **DOS source:** [DemoLoop](../WOLFSRC/WL_MAIN.C#L1404); [PlayDemo](../WOLFSRC/WL_GAME.C#L1037) +- **Timing:** 15×70 tics plus 30-tic black fades. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** TITLEPIC → CREDITSPIC +- **Sound/music:** Title/score/level tracks selected at boundaries. +- **Input/state:** Any fresh key/click opens menu. +- **Revive:** [ChangeScreen](../src/engine/WL_MAIN.c#L66); [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [demo](#demo). Open findings: presentation. + +#### credits-scores: credits → attract-scores + +**Trigger:** Attract deadline **Status:** `partial`. + +- **DOS source:** [DemoLoop](../WOLFSRC/WL_MAIN.C#L1404); [PlayDemo](../WOLFSRC/WL_GAME.C#L1037) +- **Timing:** 10×70 tics plus 30-tic black fades. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** CREDITSPIC → HIGHSCORESPIC +- **Sound/music:** Title/score/level tracks selected at boundaries. +- **Input/state:** Any fresh key/click opens menu. +- **Revive:** [ChangeScreen](../src/engine/WL_MAIN.c#L66); [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [demo](#demo). Open findings: presentation. + +#### scores-demo: attract-scores → demo + +**Trigger:** Attract deadline **Status:** `partial`. + +- **DOS source:** [DemoLoop](../WOLFSRC/WL_MAIN.C#L1404); [PlayDemo](../WOLFSRC/WL_GAME.C#L1037) +- **Timing:** 10×70 tics plus 30-tic black fades. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Scores → original demo overlay +- **Sound/music:** Title/score/level tracks selected at boundaries. +- **Input/state:** Any fresh key/click opens menu. +- **Revive:** [ChangeScreen](../src/engine/WL_MAIN.c#L66); [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [demo](#demo). Open findings: presentation. + +#### demo-title: demo → title + +**Trigger:** Demo ends/dies/exits or cannot start **Status:** `partial`. + +- **DOS source:** [PlayDemo](../WOLFSRC/WL_GAME.C#L1037); [DemoLoop](../WOLFSRC/WL_MAIN.C#L1404) +- **Timing:** 30-tic black fade with original gamepal reveal; simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Game → TITLEPIC. +- **Sound/music:** Stop level music; title music. +- **Input/state:** Demo commands isolated from live bindings. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [demo](#demo). Open findings: presentation. + +#### title-menu: title → menu + +**Trigger:** Fresh key or mouse **Status:** `partial`. + +- **DOS source:** [DemoLoop](../WOLFSRC/WL_MAIN.C#L1404); [US_ControlPanel](../WOLFSRC/WL_MENU.C#L332) +- **Timing:** 30-tic black fade with original gamepal reveal; simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original control-panel artwork. +- **Sound/music:** Menu track 14. +- **Input/state:** Abort demo and release its game resources. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic), [demo](#demo). Open findings: presentation. + +#### credits-menu: credits → menu + +**Trigger:** Fresh key or mouse **Status:** `partial`. + +- **DOS source:** [DemoLoop](../WOLFSRC/WL_MAIN.C#L1404); [US_ControlPanel](../WOLFSRC/WL_MENU.C#L332) +- **Timing:** 30-tic black fade with original gamepal reveal; simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original control-panel artwork. +- **Sound/music:** Menu track 14. +- **Input/state:** Abort demo and release its game resources. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic), [demo](#demo). Open findings: presentation. + +#### attract-scores-menu: attract-scores → menu + +**Trigger:** Fresh key or mouse **Status:** `partial`. + +- **DOS source:** [DemoLoop](../WOLFSRC/WL_MAIN.C#L1404); [US_ControlPanel](../WOLFSRC/WL_MENU.C#L332) +- **Timing:** 30-tic black fade with original gamepal reveal; simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original control-panel artwork. +- **Sound/music:** Menu track 14. +- **Input/state:** Abort demo and release its game resources. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic), [demo](#demo). Open findings: presentation. + +#### demo-menu: demo → menu + +**Trigger:** Fresh key or mouse **Status:** `partial`. + +- **DOS source:** [DemoLoop](../WOLFSRC/WL_MAIN.C#L1404); [US_ControlPanel](../WOLFSRC/WL_MENU.C#L332) +- **Timing:** 30-tic black fade with original gamepal reveal; simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original control-panel artwork. +- **Sound/music:** Menu track 14. +- **Input/state:** Abort demo and release its game resources. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic), [demo](#demo). Open findings: presentation. + +### New game + +#### menu-episode: menu → episode + +**Trigger:** Choose New Game **Status:** `partial`. + +- **DOS source:** [CP_NewGame](../WOLFSRC/WL_MENU.C#L66) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Episode artwork and six rows. +- **Sound/music:** Menu selection sound. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301); [DrawNewSelection](../src/engine/WL_MENU.c#L160) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### episode-difficulty: episode → difficulty + +**Trigger:** Accept episode without active game **Status:** `partial`. + +- **DOS source:** [CP_NewGame](../WOLFSRC/WL_MENU.C#L66) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Difficulty artwork/BJ faces. +- **Sound/music:** Menu sounds. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### episode-replace: episode → replace-confirm + +**Trigger:** Accept episode while game active **Status:** `partial`. + +- **DOS source:** [CP_NewGame](../WOLFSRC/WL_MENU.C#L66) +- **Timing:** 20-tic cursor blink; answer release. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** CURGAME message and blinking cursor. +- **Sound/music:** ESCPRESSEDSND / SHOOTSND by confirmation. +- **Input/state:** Y/N/Escape; gameplay frozen. +- **Revive:** [QuickDialog](../src/engine/WL_MAIN.c#L193) +- **Regression evidence:** [classic](#classic), [dos-pixels](#dos-pixels). Open findings: presentation. + +#### replace-yes: replace-confirm → difficulty + +**Trigger:** Y released **Status:** `partial`. + +- **DOS source:** [CP_NewGame](../WOLFSRC/WL_MENU.C#L66); [Confirm](../WOLFSRC/WL_MENU.C#L664) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore destination selection. +- **Sound/music:** Confirmation sounds. +- **Input/state:** Keep quick slot until difficulty accepted. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### replace-no: replace-confirm → menu + +**Trigger:** N/Escape **Status:** `partial`. + +- **DOS source:** [CP_NewGame](../WOLFSRC/WL_MENU.C#L66); [Confirm](../WOLFSRC/WL_MENU.C#L664) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore destination selection. +- **Sound/music:** Confirmation sounds. +- **Input/state:** Keep quick slot until difficulty accepted. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### difficulty-setup: difficulty → setup + +**Trigger:** Accept difficulty **Status:** `partial`. + +- **DOS source:** [CP_NewGame](../WOLFSRC/WL_MENU.C#L66); [SetupGameLevel](../WOLFSRC/WL_GAME.C#L42) +- **Timing:** Setup while simulation blocked. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Play border, status bar, first floor. +- **Sound/music:** Start level music. +- **Input/state:** Reset quick slot and input. +- **Revive:** [ChangeScreen](../src/engine/WL_MAIN.c#L66); [GameStartSelected](../src/engine/WL_PLAY.c#L52) +- **Regression evidence:** [campaign](#campaign), [classic](#classic). Open findings: presentation. + +#### episode-back: episode → menu + +**Trigger:** Escape **Status:** `partial`. + +- **DOS source:** [CP_NewGame](../WOLFSRC/WL_MENU.C#L66) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore parent artwork. +- **Sound/music:** Escape sound. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### difficulty-back: difficulty → episode + +**Trigger:** Escape **Status:** `partial`. + +- **DOS source:** [CP_NewGame](../WOLFSRC/WL_MENU.C#L66) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore parent artwork. +- **Sound/music:** Escape sound. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +### Loading + +#### setup-psyched: setup → psyched + +**Trigger:** New level, ordinary load, warp or secret routing **Status:** `partial`. + +- **DOS source:** [GameLoop](../WOLFSRC/WL_GAME.C#L45); [PreloadGraphics](../WOLFSRC/WL_INTER.C#L965) +- **Timing:** 30-tic fade in, real uncached page reads (≤32 per frontend update). +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** GETPSYCHEDPIC (48,56), index 127 background; retained HUD. +- **Sound/music:** Level music continues. +- **Input/state:** Block simulation and input. +- **Revive:** [StartPreloadGraphics](../src/engine/WL_INTER.c#L242) +- **Regression evidence:** [loading](#loading), [dos-pixels](#dos-pixels). Open findings: cache, presentation. + +#### psyched-progress: psyched → psyched + +**Trigger:** Each successfully cached non-sparse page **Status:** `partial`. + +- **DOS source:** [PreloadUpdate](../WOLFSRC/WL_INTER.C#L972); [PM_Preload](../WOLFSRC/ID_PM.C#L943) +- **Timing:** Only actual uncached pages advance; no artificial minimum. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** 214×2 bar (53,101); black remainder, 0x37 fill, 0x32 highlight except last column. +- **Sound/music:** Level track. +- **Input/state:** No Escape cancellation in DOS callback. +- **Revive:** [PreloadUpdate](../src/engine/WL_INTER.c#L221); [StepPreloadGraphics](../src/engine/WL_INTER.c#L252) +- **Regression evidence:** [loading](#loading), [dos-pixels](#dos-pixels). Open findings: cache, presentation. + +#### psyched-reveal: psyched → reveal + +**Trigger:** Cache complete then fresh acknowledgement or timeout **Status:** `partial`. + +- **DOS source:** [PreloadGraphics](../WOLFSRC/WL_INTER.C#L965) +- **Timing:** 70-tic wait, 30-tic fade out; gameplay geometry selected while black. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore bevel and game view while black. +- **Sound/music:** Level track. +- **Input/state:** Discard earlier presses; require fresh acknowledgement. +- **Revive:** [StepPreloadGraphics](../src/engine/WL_INTER.c#L252) +- **Regression evidence:** [loading](#loading). Open findings: cache, entry-fizzle, presentation. + +#### reveal-game: reveal → gameplay + +**Trigger:** Reveal completes **Status:** `partial`. + +- **DOS source:** [PlayLoop](../WOLFSRC/WL_PLAY.C#L91); [GameLoop](../WOLFSRC/WL_GAME.C#L45) +- **Timing:** Native 30-tic palette reveal replaces DOS entry fizzle. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Current viewport/HUD, Enhanced geometry fixed before visible frame. +- **Sound/music:** Level track. +- **Input/state:** Clear keys; reset simulation clock before control capture. +- **Revive:** [StepPreloadGraphics](../src/engine/WL_INTER.c#L252); [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [loading](#loading). Open findings: entry-fizzle, presentation. + +### Pause + +#### game-pause: gameplay → pause + +**Trigger:** Pause key **Status:** `partial`. + +- **DOS source:** [CheckKeys](../WOLFSRC/WL_PLAY.C#L609) +- **Timing:** Immediate picture; freeze simulation. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** PAUSEDPIC at (128,64) over game. +- **Sound/music:** SD_MusicOff; native preserves stream position. +- **Input/state:** Fresh acknowledgement only. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic), [dos-pixels](#dos-pixels). Open findings: presentation. + +#### pause-game: pause → gameplay + +**Trigger:** Fresh key **Status:** `partial`. + +- **DOS source:** [CheckKeys](../WOLFSRC/WL_PLAY.C#L609) +- **Timing:** Clock rebased; no catch-up. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Redraw game without overlay. +- **Sound/music:** Restore prior paused state. +- **Input/state:** Clear ack and held input. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### game-menu: gameplay → menu + +**Trigger:** Escape **Status:** `partial`. + +- **DOS source:** [CheckKeys](../WOLFSRC/WL_PLAY.C#L609); [US_ControlPanel](../WOLFSRC/WL_MENU.C#L332) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original menu on 4:3 interface canvas. +- **Sound/music:** Menu track. +- **Input/state:** Freeze gameplay; clear input. +- **Revive:** [Transition](../src/engine/WL_MAIN.c#L121) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### menu-game: menu → gameplay + +**Trigger:** Back to Game **Status:** `partial`. + +- **DOS source:** [US_ControlPanel](../WOLFSRC/WL_MENU.C#L332) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore viewport/HUD. +- **Sound/music:** Restore level track. +- **Input/state:** Reset simulation clock. +- **Revive:** [ChangeScreen](../src/engine/WL_MAIN.c#L66) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +### Storage + +#### save-panel: gameplay → save + +**Trigger:** F2 or menu Save **Status:** `partial`. + +- **DOS source:** [CP_SaveGame](../WOLFSRC/WL_MENU.C#L70) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original Saving/Loading slot artwork with six portable slots. +- **Sound/music:** Menu music/cursor sounds. +- **Input/state:** Saving restricted to living playable game. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [save](#save), [classic](#classic). Open findings: storage, presentation. + +#### load-panel: gameplay → load + +**Trigger:** F3 or menu Load **Status:** `partial`. + +- **DOS source:** [CP_LoadGame](../WOLFSRC/WL_MENU.C#L69) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original Saving/Loading slot artwork with six portable slots. +- **Sound/music:** Menu music/cursor sounds. +- **Input/state:** Saving restricted to living playable game. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [save](#save), [classic](#classic). Open findings: storage, presentation. + +#### menu-save: menu → save + +**Trigger:** Save row **Status:** `partial`. + +- **DOS source:** [CP_SaveGame](../WOLFSRC/WL_MENU.C#L70) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original Saving/Loading slot artwork with six portable slots. +- **Sound/music:** Menu music/cursor sounds. +- **Input/state:** Saving restricted to living playable game. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [save](#save), [classic](#classic). Open findings: storage, presentation. + +#### menu-load: menu → load + +**Trigger:** Load row **Status:** `partial`. + +- **DOS source:** [CP_LoadGame](../WOLFSRC/WL_MENU.C#L69) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original Saving/Loading slot artwork with six portable slots. +- **Sound/music:** Menu music/cursor sounds. +- **Input/state:** Saving restricted to living playable game. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [save](#save), [classic](#classic). Open findings: storage, presentation. + +#### save-work: save → disk + +**Trigger:** Accept slot; edit/overwrite confirmation for save **Status:** `partial`. + +- **DOS source:** [CP_SaveGame](../WOLFSRC/WL_MENU.C#L70); [DrawLSAction](../WOLFSRC/WL_MENU.C#L1343) +- **Timing:** Nonblocking presentation phases around synchronous atomic I/O. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original disk window and alternating disk pictures. +- **Sound/music:** Menu effects; loading restores level music. +- **Input/state:** Confirmation answer release; validation errors preserve active game. +- **Revive:** [HandleSaveMenu](../src/engine/WL_SAVE_MENU.c#L73) +- **Regression evidence:** [save](#save), [interface](#interface), [dos-pixels](#dos-pixels). Open findings: storage, presentation. + +#### load-work: load → disk + +**Trigger:** Accept slot; edit/overwrite confirmation for save **Status:** `partial`. + +- **DOS source:** [CP_LoadGame](../WOLFSRC/WL_MENU.C#L69); [DrawLSAction](../WOLFSRC/WL_MENU.C#L1343) +- **Timing:** Nonblocking presentation phases around synchronous atomic I/O. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original disk window and alternating disk pictures. +- **Sound/music:** Menu effects; loading restores level music. +- **Input/state:** Confirmation answer release; validation errors preserve active game. +- **Revive:** [HandleSaveMenu](../src/engine/WL_SAVE_MENU.c#L73) +- **Regression evidence:** [save](#save), [interface](#interface), [dos-pixels](#dos-pixels). Open findings: storage, presentation. + +#### ordinary-load-setup: disk → setup + +**Trigger:** Ordinary load succeeds **Status:** `partial`. + +- **DOS source:** [CP_LoadGame](../WOLFSRC/WL_MENU.C#L69); [GameLoop](../WOLFSRC/WL_GAME.C#L45) +- **Timing:** Ordinary load requests Get Psyched. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Retain saved game and current display settings. +- **Sound/music:** Restore saved logical digi mode and level track. +- **Input/state:** Clear input; no gameplay advance. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301); [GameRestoreClock](../src/engine/WL_PLAY.c#L236) +- **Regression evidence:** [save](#save), [loading](#loading). Open findings: storage, presentation. + +#### save-return: disk → gameplay + +**Trigger:** Save succeeds **Status:** `partial`. + +- **DOS source:** [CP_SaveGame](../WOLFSRC/WL_MENU.C#L70) +- **Timing:** Finish disk phase; resume clock. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Redraw game and border. +- **Sound/music:** Level track. +- **Input/state:** No reused save key. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [save](#save), [classic](#classic). Open findings: storage, presentation. + +#### save-cancel: save → menu + +**Trigger:** Escape from ordinary menu operation **Status:** `partial`. + +- **DOS source:** [CP_SaveGame](../WOLFSRC/WL_MENU.C#L70) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller; F-key caller returns directly to gameplay. +- **Sound/music:** Escape sound. +- **Input/state:** No slot established on cancel. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [classic](#classic), [save](#save). Open findings: storage, presentation. + +#### load-cancel: load → menu + +**Trigger:** Escape from ordinary menu operation **Status:** `partial`. + +- **DOS source:** [CP_LoadGame](../WOLFSRC/WL_MENU.C#L69) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller; F-key caller returns directly to gameplay. +- **Sound/music:** Escape sound. +- **Input/state:** No slot established on cancel. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [classic](#classic), [save](#save). Open findings: storage, presentation. + +#### quicksave: gameplay → quick-disk + +**Trigger:** F8 with established valid slot **Status:** `partial`. + +- **DOS source:** [CP_CheckQuick](../WOLFSRC/WL_MENU.C#L338) +- **Timing:** Start/work/finish phases; no confirmation. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Saving activity window. +- **Sound/music:** Effects; no gameplay advancement. +- **Input/state:** First-use F8 opens ordinary selection instead. +- **Revive:** [QuickSave](../src/engine/WL_MAIN.c#L215) +- **Regression evidence:** [classic](#classic), [interface](#interface). Open findings: storage, presentation. + +#### quickload-confirm: gameplay → quick-confirm + +**Trigger:** F9 established slot **Status:** `partial`. + +- **DOS source:** [CP_CheckQuick](../WOLFSRC/WL_MENU.C#L338) +- **Timing:** Blink/release confirmation. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Named quickload message in 160-pixel area. +- **Sound/music:** Confirmation effects. +- **Input/state:** Y/N/Escape; invalid slot opens ordinary selection. +- **Revive:** [QuickDialog](../src/engine/WL_MAIN.c#L193) +- **Regression evidence:** [classic](#classic). Open findings: storage, presentation. + +#### quickload-yes: quick-confirm → quick-disk + +**Trigger:** Y released **Status:** `partial`. + +- **DOS source:** [CP_LoadGame](../WOLFSRC/WL_MENU.C#L69) +- **Timing:** Synchronous validated load during work phase. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Loading disk artwork. +- **Sound/music:** Restore level music. +- **Input/state:** Revalidate file at load time. +- **Revive:** [QuickActivity](../src/engine/WL_MAIN.c#L209) +- **Regression evidence:** [classic](#classic), [save](#save). Open findings: storage, presentation. + +#### quickload-no: quick-confirm → gameplay + +**Trigger:** N/Escape **Status:** `partial`. + +- **DOS source:** [CP_CheckQuick](../WOLFSRC/WL_MENU.C#L338) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore gameplay. +- **Sound/music:** Level track. +- **Input/state:** Preserve active game. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### quick-resume: quick-disk → gameplay + +**Trigger:** Established quick operation succeeds **Status:** `partial`. + +- **DOS source:** [CP_LoadGame](../WOLFSRC/WL_MENU.C#L69); [CP_CheckQuick](../WOLFSRC/WL_MENU.C#L338) +- **Timing:** Direct play-loop return, clock reset. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore border/game; no Get Psyched. +- **Sound/music:** Level track. +- **Input/state:** No simulation during disk phases. +- **Revive:** [GamePreloadConsumed](../src/engine/WL_MAIN.c#L449) +- **Regression evidence:** [classic](#classic). Open findings: storage, presentation. + +#### storage-error: quick-disk → message + +**Trigger:** Load/write fails validation or I/O **Status:** `partial`. + +- **DOS source:** [CP_LoadGame](../WOLFSRC/WL_MENU.C#L69) +- **Timing:** Wait for acknowledgement. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Native explanatory error message. +- **Sound/music:** No new game sound. +- **Input/state:** Retain active game, file and rankings where supported. +- **Revive:** [QuickDialog](../src/engine/WL_MAIN.c#L193) +- **Regression evidence:** [save](#save), [classic](#classic). Open findings: storage. + +#### message-return: message → gameplay + +**Trigger:** Fresh key **Status:** `partial`. + +- **DOS source:** [CheckKeys](../WOLFSRC/WL_PLAY.C#L609) +- **Timing:** Clock rebase. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Redraw game. +- **Sound/music:** Restore level track. +- **Input/state:** Consume acknowledgement. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +### Death + +#### death-turn: gameplay → death-turn + +**Trigger:** Health reaches zero or End Game **Status:** `partial`. + +- **DOS source:** [Died](../WOLFSRC/WL_GAME.C#L1107) +- **Timing:** 2 degrees/tic; shortest arc; 180° chooses negative; float intermediate atan2. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Held weapon sentinel -1; retain HUD weapon icon. +- **Sound/music:** Stop music; PLAYERDEATHSND. +- **Input/state:** Turn/fizzle input discarded. +- **Revive:** [Died](../src/engine/WL_PLAY.c#L81) +- **Regression evidence:** [death](#death), [classic](#classic). Open findings: presentation. + +#### death-fizzle: death-turn → red-fizzle + +**Trigger:** Attacker angle reached **Status:** `partial`. + +- **DOS source:** [Died](../WOLFSRC/WL_GAME.C#L1107); [FizzleFade](../WOLFSRC/ID_VH.C#L462) +- **Timing:** Enter fizzle on final turn tic; 64000/70 candidates per tic. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Index 4 with 17-bit polynomial. +- **Sound/music:** Death sound continues. +- **Input/state:** Unabortable fizzle. +- **Revive:** [Died](../src/engine/WL_PLAY.c#L81) +- **Regression evidence:** [death](#death). Open findings: fizzle-clip, presentation. + +#### death-ack: red-fizzle → death-ack + +**Trigger:** Polynomial completes **Status:** `partial`. + +- **DOS source:** [Died](../WOLFSRC/WL_GAME.C#L1107) +- **Timing:** 100-tic wait or fresh acknowledgement. DOS then calls SD_WaitSoundDone for the active FM/PC effect; native has no separate completion gate. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Red viewport/HUD retained. +- **Sound/music:** Death sound continues; sound-enabled continuation timing has not received an executed-DOS comparison. +- **Input/state:** Clear turn/fizzle presses. +- **Revive:** [Died](../src/engine/WL_PLAY.c#L81) +- **Regression evidence:** [death](#death). Open findings: presentation, audio. + +#### death-restart: death-ack → restart + +**Trigger:** Lives remain **Status:** `partial`. + +- **DOS source:** [Died](../WOLFSRC/WL_GAME.C#L1107); [GameLoop](../WOLFSRC/WL_GAME.C#L45) +- **Timing:** Rebuild same level; skip Get Psyched. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Pistol, 100 health, STARTAMMO, no keys; entry score. +- **Sound/music:** Restart level track. +- **Input/state:** Clear held/ack input. +- **Revive:** [Died](../src/engine/WL_PLAY.c#L81) +- **Regression evidence:** [death](#death), [campaign](#campaign). Open findings: presentation. + +#### restart-reveal: restart → gameplay + +**Trigger:** Level rebuild succeeds **Status:** `partial`. + +- **DOS source:** [GameLoop](../WOLFSRC/WL_GAME.C#L45) +- **Timing:** DOS sets fizzlein for the same-floor restart; Revive redraws the game immediately without a separate reveal phase. +- **Palette:** Original gamepal; no native restart fade/fizzle. +- **Artwork/layout:** Original play border/HUD. +- **Sound/music:** Level track. +- **Input/state:** Rebase clock. +- **Revive:** [Died](../src/engine/WL_PLAY.c#L81) +- **Regression evidence:** [death](#death). Open findings: entry-fizzle, presentation. + +#### death-final: death-ack → qualification + +**Trigger:** Lives become negative **Status:** `partial`. + +- **DOS source:** [GameLoop](../WOLFSRC/WL_GAME.C#L45); [CheckHighScore](../WOLFSRC/WL_INTER.C#L1190) +- **Timing:** 30-tic black fade with original gamepal reveal; simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** No Game Over card in this DOS source. +- **Sound/music:** Score music 23. +- **Input/state:** Clear input. +- **Revive:** [HighScores_Insert](../src/engine/WL_MAIN.c#L379) +- **Regression evidence:** [classic](#classic), [scores](#scores). Open findings: presentation. + +### Progression + +#### exit-completion: gameplay → completion + +**Trigger:** Normal elevator exit **Status:** `partial`. + +- **DOS source:** [GameLoop](../WOLFSRC/WL_GAME.C#L45); [LevelCompleted](../WOLFSRC/WL_INTER.C#L413) +- **Timing:** Source-based counters, sound waits and 30-VBL boundaries. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original floor completed, ratios, bonus and BJ breathing. +- **Sound/music:** Completion music/effects. +- **Input/state:** First press skips counts; separate press continues. +- **Revive:** [GameStep](../src/engine/WL_PLAY.c#L98); [StartLevelIntermission](../src/engine/WL_INTER.c#L167) +- **Regression evidence:** [campaign](#campaign). Open findings: presentation. + +#### secret-completion: gameplay → secret-completion + +**Trigger:** Secret elevator exit **Status:** `partial`. + +- **DOS source:** [GameLoop](../WOLFSRC/WL_GAME.C#L45) +- **Timing:** Intermission counters/ack. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Normal-floor completion before secret routing. +- **Sound/music:** Completion music/effects. +- **Input/state:** Separate continuation acknowledgement. +- **Revive:** [GameStep](../src/engine/WL_PLAY.c#L98) +- **Regression evidence:** [campaign](#campaign), [loading](#loading). Open findings: presentation. + +#### next-setup: completion → setup + +**Trigger:** Intermission acknowledged **Status:** `partial`. + +- **DOS source:** [GameLoop](../WOLFSRC/WL_GAME.C#L45) +- **Timing:** oldscore updated; setup/preload. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Next floor; retain inventory, reset keys. +- **Sound/music:** Next floor music. +- **Input/state:** Clear ack. +- **Revive:** [GameStep](../src/engine/WL_PLAY.c#L98) +- **Regression evidence:** [campaign](#campaign), [loading](#loading). Open findings: presentation. + +#### secret-entry: secret-completion → setup + +**Trigger:** Intermission acknowledged **Status:** `partial`. + +- **DOS source:** [GameLoop](../WOLFSRC/WL_GAME.C#L45) +- **Timing:** Ordinary setup/preload. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Route to floor 9 (zero based). +- **Sound/music:** Secret floor track. +- **Input/state:** No input carry. +- **Revive:** [GameStep](../src/engine/WL_PLAY.c#L98) +- **Regression evidence:** [campaign](#campaign), [loading](#loading). Open findings: presentation. + +#### secret-return: completion → setup + +**Trigger:** Leaving mapon 9 **Status:** `partial`. + +- **DOS source:** [ElevatorBackTo](../WOLFSRC/WL_GAME.C#L39); [GameLoop](../WOLFSRC/WL_GAME.C#L45) +- **Timing:** Episode-specific ElevatorBackTo; ordinary preload. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Secret floor completed card and 15000 bonus. +- **Sound/music:** Destination track. +- **Input/state:** Separate acknowledgement. +- **Revive:** [GameStep](../src/engine/WL_PLAY.c#L98) +- **Regression evidence:** [campaign](#campaign), [loading](#loading). Open findings: presentation. + +### Victory + +#### boss-victory: gameplay → boss-replay + +**Trigger:** Boss dies / victory tile **Status:** `partial`. + +- **DOS source:** [A_StartDeathCam](../WOLFSRC/WL_ACT2.C#L158); [Victory](../WOLFSRC/WL_INTER.C#L103) +- **Timing:** Original actor states; logical digi death delay 140 versus 5 tics. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** BJ run/jump or boss death-camera/replay by episode. +- **Sound/music:** Boss effects and victory track. +- **Input/state:** No save during cinematic. +- **Revive:** [DeathCameraActive](../src/engine/WL_VICTORY.c#L37); [GameStep](../src/engine/WL_PLAY.c#L98) +- **Regression evidence:** [finale](#finale). Open findings: presentation. + +#### victory-stats: boss-replay → victory + +**Trigger:** Cinematic finishes **Status:** `partial`. + +- **DOS source:** [Victory](../WOLFSRC/WL_INTER.C#L103) +- **Timing:** 30-tic black fade with original gamepal reveal; simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** YOU WIN, eight-floor averages/time/code and HUD. +- **Sound/music:** Victory track. +- **Input/state:** Fresh acknowledgement. +- **Revive:** [DrawVictory](../src/engine/WL_INTER.c#L104); [GameStep](../src/engine/WL_PLAY.c#L98) +- **Regression evidence:** [finale](#finale). Open findings: presentation. + +#### victory-article: victory → article + +**Trigger:** Acknowledge victory statistics **Status:** `partial`. + +- **DOS source:** [Victory](../WOLFSRC/WL_INTER.C#L103); [EndText](../WOLFSRC/WL_TEXT.C#L800) +- **Timing:** Native page state; DOS layout commands retained. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original ending article text/pictures. +- **Sound/music:** Ending music. +- **Input/state:** Arrows/Enter/PageUp/Down; Escape exits. +- **Revive:** [StartEndText](../src/engine/WL_TEXT.c#L108) +- **Regression evidence:** [finale](#finale). Open findings: presentation. + +#### article-scores: article → qualification + +**Trigger:** Last page/escape **Status:** `partial`. + +- **DOS source:** [EndText](../WOLFSRC/WL_TEXT.C#L800); [GameLoop](../WOLFSRC/WL_GAME.C#L45) +- **Timing:** 30-tic black fade with original gamepal reveal; simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original high-score panel. +- **Sound/music:** Score music 23. +- **Input/state:** Clear article input. +- **Revive:** [StepEndText](../src/engine/WL_TEXT.c#L128); [HighScores_Insert](../src/engine/WL_MAIN.c#L379) +- **Regression evidence:** [finale](#finale), [scores](#scores). Open findings: presentation. + +### High scores + +#### qualify: qualification → name-entry + +**Trigger:** Strict score/floor qualification **Status:** `partial`. + +- **DOS source:** [CheckHighScore](../WOLFSRC/WL_INTER.C#L1190); [US_LineInput](../WOLFSRC/ID_US_1.C#L534) +- **Timing:** 30-tic reveal; source editor limits. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Seven-entry table, blank inserted name and I-bar. +- **Sound/music:** Score track. +- **Input/state:** 57-character / 100-pixel pre-insertion limits; Enter/Escape. +- **Revive:** [ChangeScreen](../src/engine/WL_MAIN.c#L66); [HighScores_Insert](../src/engine/WL_HIGHSCORES.c#L74) +- **Regression evidence:** [scores](#scores). Open findings: presentation. + +#### not-qualified: qualification → results + +**Trigger:** No rank **Status:** `partial`. + +- **DOS source:** [CheckHighScore](../WOLFSRC/WL_INTER.C#L1190) +- **Timing:** 500-tic hold after 30-tic reveal. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Seven-entry table. +- **Sound/music:** Score track. +- **Input/state:** Any fresh key continues. +- **Revive:** [ChangeScreen](../src/engine/WL_MAIN.c#L66) +- **Regression evidence:** [scores](#scores), [classic](#classic). Open findings: presentation. + +#### name-save: name-entry → title + +**Trigger:** Enter or Escape finishes editor **Status:** `partial`. + +- **DOS source:** [CheckHighScore](../WOLFSRC/WL_INTER.C#L1190) +- **Timing:** 30-tic black fade with original gamepal reveal; simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Title after entry; Escape keeps inserted blank name. +- **Sound/music:** Title track. +- **Input/state:** Atomic native persistence; failure retains session rankings and reports message. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301); [HighScores_Save](../src/engine/WL_HIGHSCORES.c#L62) +- **Regression evidence:** [scores](#scores). Open findings: storage, presentation. + +#### results-title: results → title + +**Trigger:** Timeout/fresh key **Status:** `partial`. + +- **DOS source:** [CheckHighScore](../WOLFSRC/WL_INTER.C#L1190); [DemoLoop](../WOLFSRC/WL_MAIN.C#L1404) +- **Timing:** 30-tic black fade with original gamepal reveal; simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Title/attract cycle. +- **Sound/music:** Title track. +- **Input/state:** Consume acknowledgement. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [scores](#scores), [classic](#classic). Open findings: presentation. + +### Quit + +#### quit-menu: menu → quit-confirm + +**Trigger:** Quit row/Escape or F10 **Status:** `partial`. + +- **DOS source:** [CP_Quit](../WOLFSRC/WL_MENU.C#L492); [CP_CheckQuick](../WOLFSRC/WL_MENU.C#L338) +- **Timing:** 20-tic cursor blink; wait for answer release. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Nine original sayings; WindowH 200 menu / 160 gameplay. +- **Sound/music:** Confirmation sound. +- **Input/state:** Y/N/Escape, keyboard only; separate UI entropy protects gameplay RNG. +- **Revive:** [QuitMessage](../src/engine/WL_MAIN.c#L35); [QuickDialog](../src/engine/WL_MAIN.c#L193) +- **Regression evidence:** [classic](#classic), [dos-pixels](#dos-pixels). Open findings: ui-rng, presentation. + +#### quit-game: gameplay → quit-confirm + +**Trigger:** Quit row/Escape or F10 **Status:** `partial`. + +- **DOS source:** [CP_Quit](../WOLFSRC/WL_MENU.C#L492); [CP_CheckQuick](../WOLFSRC/WL_MENU.C#L338) +- **Timing:** 20-tic cursor blink; wait for answer release. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Nine original sayings; WindowH 200 menu / 160 gameplay. +- **Sound/music:** Confirmation sound. +- **Input/state:** Y/N/Escape, keyboard only; separate UI entropy protects gameplay RNG. +- **Revive:** [QuitMessage](../src/engine/WL_MAIN.c#L35); [QuickDialog](../src/engine/WL_MAIN.c#L193) +- **Regression evidence:** [classic](#classic), [dos-pixels](#dos-pixels). Open findings: ui-rng, presentation. + +#### quit-no: quit-confirm → menu + +**Trigger:** N/Escape from menu **Status:** `partial`. + +- **DOS source:** [CP_Quit](../WOLFSRC/WL_MENU.C#L492) +- **Timing:** Menu redraw/return fade. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore menu; F10 caller restores gameplay. +- **Sound/music:** Menu or level track. +- **Input/state:** Consume answer. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### quit-yes: quit-confirm → exit + +**Trigger:** Y released **Status:** `partial`. + +- **DOS source:** [CP_Quit](../WOLFSRC/WL_MENU.C#L492) +- **Timing:** 10-tic fade; portable resource teardown. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Menu dark-red fade then SDL shutdown. +- **Sound/music:** Stop music and sound before fade. +- **Input/state:** No reused key; window close exits directly. +- **Revive:** [Transition](../src/engine/WL_MAIN.c#L121) +- **Regression evidence:** [classic](#classic). Open findings: hardware, presentation. + +### Other panels + +#### panel-sound: menu → sound + +**Trigger:** Menu selection or corresponding F key **Status:** `partial`. + +- **DOS source:** [CP_Sound](../WOLFSRC/WL_MENU.C#L67) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original sound labels plus independent native volumes +- **Sound/music:** Menu effects; boss key mutes music. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [BeginSoundSettings](../src/engine/WL_MENU.c#L246) +- **Regression evidence:** [audio](#audio). Open findings: audio, presentation. + +#### return-sound: sound → menu + +**Trigger:** Escape/accept; direct F-key caller returns to game **Status:** `partial`. + +- **DOS source:** [CP_Sound](../WOLFSRC/WL_MENU.C#L67) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller. +- **Sound/music:** Restore caller track. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [audio](#audio). Open findings: audio, presentation. + +#### panel-controls: menu → controls + +**Trigger:** Menu selection or corresponding F key **Status:** `partial`. + +- **DOS source:** [CP_Control](../WOLFSRC/WL_MENU.C#L68) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Classic/Modern bindings and mouse settings +- **Sound/music:** Menu effects; boss key mutes music. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [BeginControlsMenu](../src/engine/WL_CONTROLS_MENU.c#L99) +- **Regression evidence:** [interface](#interface). Open findings: hardware. + +#### return-controls: controls → menu + +**Trigger:** Escape/accept; direct F-key caller returns to game **Status:** `partial`. + +- **DOS source:** [CP_Control](../WOLFSRC/WL_MENU.C#L68) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller. +- **Sound/music:** Restore caller track. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [interface](#interface). Open findings: hardware. + +#### panel-display: controls → display + +**Trigger:** Select native Display settings in Controls **Status:** `partial`. + +- **DOS source:** [CP_ChangeView](../WOLFSRC/WL_MENU.C#L71) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Native output settings, no DOS equivalent +- **Sound/music:** Menu effects; boss key mutes music. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [BeginDisplayMenu](../src/engine/WL_DISPLAY.c#L61) +- **Regression evidence:** [loading](#loading). Open findings: hardware. + +#### return-display: display → controls + +**Trigger:** Escape to Controls **Status:** `partial`. + +- **DOS source:** [CP_ChangeView](../WOLFSRC/WL_MENU.C#L71) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller. +- **Sound/music:** Restore caller track. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [loading](#loading). Open findings: hardware. + +#### panel-view: menu → view + +**Trigger:** Menu selection or corresponding F key **Status:** `partial`. + +- **DOS source:** [CP_ChangeView](../WOLFSRC/WL_MENU.C#L71) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original sizes 4–19 and border preview +- **Sound/music:** Menu effects; boss key mutes music. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [BeginViewMenu](../src/engine/WL_VIEW.c#L35) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### return-view: view → menu + +**Trigger:** Escape/accept; direct F-key caller returns to game **Status:** `partial`. + +- **DOS source:** [CP_ChangeView](../WOLFSRC/WL_MENU.C#L71) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller. +- **Sound/music:** Restore caller track. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### panel-boss: menu → boss + +**Trigger:** Menu selection or corresponding F key **Status:** `partial`. + +- **DOS source:** [BossKey](../WOLFSRC/WL_MENU.C#L351) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** GOODTIMES C> rendered using game font +- **Sound/music:** Menu effects; boss key mutes music. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [ChangeScreen](../src/engine/WL_MAIN.c#L66) +- **Regression evidence:** [classic](#classic). Open findings: hardware. + +#### return-boss: boss → menu + +**Trigger:** Escape/accept; direct F-key caller returns to game **Status:** `partial`. + +- **DOS source:** [BossKey](../WOLFSRC/WL_MENU.C#L351) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller. +- **Sound/music:** Restore caller track. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [classic](#classic). Open findings: hardware. + +### Optional routes + +#### jukebox: signon → jukebox + +**Trigger:** M held at startup/sign-on or --jukebox **Status:** `partial`. + +- **DOS source:** [DoJukebox](../WOLFSRC/WL_MAIN.C#L1015) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Robert’s Jukebox, three six-song banks. +- **Sound/music:** 18 original track indices. +- **Input/state:** Monotonic bank choice replaces DOS time. +- **Revive:** [DemoLoopJukebox](../src/engine/WL_MAIN.c#L249) +- **Regression evidence:** [hidden](#hidden). Open findings: hardware, presentation. + +#### jukebox-return: jukebox → title + +**Trigger:** Escape **Status:** `partial`. + +- **DOS source:** [DoJukebox](../WOLFSRC/WL_MAIN.C#L1015) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Title. +- **Sound/music:** Title music. +- **Input/state:** Clear input. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [hidden](#hidden). Open findings: presentation. + +#### debug-warp: gameplay → warp + +**Trigger:** Unlocked Tab-W **Status:** `partial`. + +- **DOS source:** [DebugKeys](../WOLFSRC/WL_DEBUG.C#L27) +- **Timing:** Freeze while editing. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original warp prompt. +- **Sound/music:** Current level track. +- **Input/state:** Validate floors 1–10; Escape cancels. +- **Revive:** [HiddenKeys](../src/engine/WL_MAIN.c#L256) +- **Regression evidence:** [hidden](#hidden). Open findings: hardware. + +#### warp-setup: warp → setup + +**Trigger:** Valid floor entered **Status:** `partial`. + +- **DOS source:** [GameLoop](../WOLFSRC/WL_GAME.C#L45) +- **Timing:** Retain inventory; restore entry score. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Ordinary level setup and Get Psyched. +- **Sound/music:** Destination track. +- **Input/state:** Clear input. +- **Revive:** [GameWarp](../src/engine/WL_PLAY.c#L71) +- **Regression evidence:** [hidden](#hidden), [loading](#loading). Open findings: presentation. + +#### cheat-message: gameplay → message + +**Trigger:** MLI/BAT/debug message **Status:** `partial`. + +- **DOS source:** [CheckKeys](../WOLFSRC/WL_PLAY.C#L609); [DebugKeys](../WOLFSRC/WL_DEBUG.C#L27) +- **Timing:** Paused acknowledgement; MLI +42000 tics. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original cheat/debug text. +- **Sound/music:** Current track. +- **Input/state:** MLI clears score, supplies health/ammo/keys/chaingun. +- **Revive:** [HiddenKeys](../src/engine/WL_MAIN.c#L256) +- **Regression evidence:** [hidden](#hidden). Open findings: hardware. + +### Errors + +#### asset-error: setup → error + +**Trigger:** Invalid/missing/corrupt level data **Status:** `partial`. + +- **DOS source:** [SetupGameLevel](../WOLFSRC/WL_GAME.C#L42) +- **Timing:** No simulation; release level resources. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Native readable error. +- **Sound/music:** Stop level music/effects. +- **Input/state:** Fresh key to menu. +- **Revive:** [GameError](../src/engine/WL_MAIN.c#L53) +- **Regression evidence:** [save](#save). Open findings: storage. + +#### error-menu: error → menu + +**Trigger:** Fresh key **Status:** `partial`. + +- **DOS source:** [Quit](../WOLFSRC/WL_MAIN.C#L65) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Control panel. +- **Sound/music:** Menu track. +- **Input/state:** Consume error acknowledgement. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: storage. + +### High scores + +#### menu-scores: menu → scores + +**Trigger:** View Scores with no active game **Status:** `partial`. + +- **DOS source:** [CP_ViewScores](../WOLFSRC/WL_MENU.C#L893) +- **Timing:** 10-tic menu fade; wait for fresh key. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** CREDITSPIC → HIGHSCORESPIC +- **Sound/music:** Title/score/level tracks selected at boundaries. +- **Input/state:** Fresh key returns to main menu. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic), [scores](#scores). Open findings: presentation. + +#### scores-menu: scores → menu + +**Trigger:** Fresh key **Status:** `partial`. + +- **DOS source:** [CheckHighScore](../WOLFSRC/WL_INTER.C#L1190); [DemoLoop](../WOLFSRC/WL_MAIN.C#L1404) +- **Timing:** 10-tic menu fade. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Title/attract cycle. +- **Sound/music:** Title track. +- **Input/state:** Consume acknowledgement. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [scores](#scores), [classic](#classic). Open findings: presentation. + +### Pause + +#### menu-attract: menu → title + +**Trigger:** Back to Demo with no live game **Status:** `partial`. + +- **DOS source:** [US_ControlPanel](../WOLFSRC/WL_MENU.C#L332) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original TITLEPIC and restarted attract cycle. +- **Sound/music:** Title track 7. +- **Input/state:** Clear selection input. +- **Revive:** [ChangeScreen](../src/engine/WL_MAIN.c#L66) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +### Other panels + +#### game-sound: gameplay → sound + +**Trigger:** Corresponding F key during living gameplay **Status:** `partial`. + +- **DOS source:** [CP_Sound](../WOLFSRC/WL_MENU.C#L67) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original sound labels plus independent native volumes +- **Sound/music:** Menu effects; boss key mutes music. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [BeginSoundSettings](../src/engine/WL_MENU.c#L246) +- **Regression evidence:** [audio](#audio). Open findings: audio, presentation. + +#### sound-game: sound → gameplay + +**Trigger:** Accept/Escape from direct F-key panel **Status:** `partial`. + +- **DOS source:** [CP_Sound](../WOLFSRC/WL_MENU.C#L67) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller. +- **Sound/music:** Restore caller track. +- **Input/state:** Rebase game clock and clear panel input. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [audio](#audio). Open findings: audio, presentation. + +#### game-controls: gameplay → controls + +**Trigger:** Corresponding F key during living gameplay **Status:** `partial`. + +- **DOS source:** [CP_Control](../WOLFSRC/WL_MENU.C#L68) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Classic/Modern bindings and mouse settings +- **Sound/music:** Menu effects; boss key mutes music. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [BeginControlsMenu](../src/engine/WL_CONTROLS_MENU.c#L99) +- **Regression evidence:** [interface](#interface). Open findings: hardware. + +#### controls-game: controls → gameplay + +**Trigger:** Accept/Escape from direct F-key panel **Status:** `partial`. + +- **DOS source:** [CP_Control](../WOLFSRC/WL_MENU.C#L68) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller. +- **Sound/music:** Restore caller track. +- **Input/state:** Rebase game clock and clear panel input. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [interface](#interface). Open findings: hardware. + +#### game-view: gameplay → view + +**Trigger:** Corresponding F key during living gameplay **Status:** `partial`. + +- **DOS source:** [CP_ChangeView](../WOLFSRC/WL_MENU.C#L71) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original sizes 4–19 and border preview +- **Sound/music:** Menu effects; boss key mutes music. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [BeginViewMenu](../src/engine/WL_VIEW.c#L35) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### view-game: view → gameplay + +**Trigger:** Accept/Escape from direct F-key panel **Status:** `partial`. + +- **DOS source:** [CP_ChangeView](../WOLFSRC/WL_MENU.C#L71) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller. +- **Sound/music:** Restore caller track. +- **Input/state:** Rebase game clock and clear panel input. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### game-boss: gameplay → boss + +**Trigger:** Corresponding F key during living gameplay **Status:** `partial`. + +- **DOS source:** [BossKey](../WOLFSRC/WL_MENU.C#L351) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** GOODTIMES C> rendered using game font +- **Sound/music:** Menu effects; boss key mutes music. +- **Input/state:** Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input. +- **Revive:** [ChangeScreen](../src/engine/WL_MAIN.c#L66) +- **Regression evidence:** [classic](#classic). Open findings: hardware. + +#### boss-game: boss → gameplay + +**Trigger:** Accept/Escape from direct F-key panel **Status:** `partial`. + +- **DOS source:** [BossKey](../WOLFSRC/WL_MENU.C#L351) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller. +- **Sound/music:** Restore caller track. +- **Input/state:** Rebase game clock and clear panel input. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [classic](#classic). Open findings: hardware. + +### Storage + +#### save-cancel-game: save → gameplay + +**Trigger:** Escape from direct F2 panel **Status:** `partial`. + +- **DOS source:** [CP_SaveGame](../WOLFSRC/WL_MENU.C#L70) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller; F-key caller returns directly to gameplay. +- **Sound/music:** Escape sound. +- **Input/state:** No slot established on cancel. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [classic](#classic), [save](#save). Open findings: storage, presentation. + +#### load-cancel-game: load → gameplay + +**Trigger:** Escape from direct F3 panel **Status:** `partial`. + +- **DOS source:** [CP_LoadGame](../WOLFSRC/WL_MENU.C#L69) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore caller; F-key caller returns directly to gameplay. +- **Sound/music:** Escape sound. +- **Input/state:** No slot established on cancel. +- **Revive:** [ReturnPanel](../src/engine/WL_MAIN.c#L189) +- **Regression evidence:** [classic](#classic), [save](#save). Open findings: storage, presentation. + +### Quit + +#### quit-no-game: quit-confirm → gameplay + +**Trigger:** N/Escape from F10 confirmation **Status:** `partial`. + +- **DOS source:** [CP_Quit](../WOLFSRC/WL_MENU.C#L492) +- **Timing:** Menu redraw/return fade. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore live game and border. +- **Sound/music:** Level track. +- **Input/state:** Consume answer. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +### Death + +#### end-game: gameplay → end-confirm + +**Trigger:** F7 or End Game row **Status:** `partial`. + +- **DOS source:** [CP_EndGame](../WOLFSRC/WL_MENU.C#L864); [CP_CheckQuick](../WOLFSRC/WL_MENU.C#L338) +- **Timing:** Blink/release confirmation. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original ENDGAMESTR message and confirmation cursor. +- **Sound/music:** Confirmation effects. +- **Input/state:** Y/N/Escape; freeze active game. +- **Revive:** [QuickDialog](../src/engine/WL_MAIN.c#L193) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### end-menu: menu → end-confirm + +**Trigger:** F7 or End Game row **Status:** `partial`. + +- **DOS source:** [CP_EndGame](../WOLFSRC/WL_MENU.C#L864); [CP_CheckQuick](../WOLFSRC/WL_MENU.C#L338) +- **Timing:** Blink/release confirmation. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Original ENDGAMESTR message and confirmation cursor. +- **Sound/music:** Confirmation effects. +- **Input/state:** Y/N/Escape; freeze active game. +- **Revive:** [QuickDialog](../src/engine/WL_MAIN.c#L193) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### end-yes: end-confirm → death-turn + +**Trigger:** Y released **Status:** `partial`. + +- **DOS source:** [Died](../WOLFSRC/WL_GAME.C#L1107) +- **Timing:** 2 degrees/tic; shortest arc; 180° chooses negative; float intermediate atan2. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Held weapon sentinel -1; retain HUD weapon icon. +- **Sound/music:** Stop music; PLAYERDEATHSND. +- **Input/state:** Set lives=0, ex_died; clear quick slot and answer input. +- **Revive:** [Died](../src/engine/WL_PLAY.c#L81) +- **Regression evidence:** [death](#death), [classic](#classic). Open findings: presentation. + +#### end-no: end-confirm → gameplay + +**Trigger:** N/Escape from gameplay End Game **Status:** `partial`. + +- **DOS source:** [CP_CheckQuick](../WOLFSRC/WL_MENU.C#L338) +- **Timing:** 10-tic menu dark-red fade (43,0,0); simulation frozen. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore gameplay. +- **Sound/music:** Level track. +- **Input/state:** Preserve active game. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +#### end-no-menu: end-confirm → menu + +**Trigger:** N/Escape from menu End Game **Status:** `partial`. + +- **DOS source:** [CP_Quit](../WOLFSRC/WL_MENU.C#L492) +- **Timing:** Menu redraw/return fade. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Restore menu; F10 caller restores gameplay. +- **Sound/music:** Menu or level track. +- **Input/state:** Consume answer. +- **Revive:** [StepDemoLoop](../src/engine/WL_MAIN.c#L301) +- **Regression evidence:** [classic](#classic). Open findings: presentation. + +### Errors + +#### preload-error: psyched → error + +**Trigger:** Asset read/allocation fails during preload **Status:** `partial`. + +- **DOS source:** [PreloadGraphics](../WOLFSRC/WL_INTER.C#L965) +- **Timing:** No simulation; release level resources. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Native readable error. +- **Sound/music:** Stop level music/effects. +- **Input/state:** Fresh key to menu. +- **Revive:** [GameError](../src/engine/WL_MAIN.c#L53) +- **Regression evidence:** [loading](#loading), [save](#save). Open findings: storage. + +### Storage + +#### save-error: save → save + +**Trigger:** Write or overwrite fails **Status:** `partial`. + +- **DOS source:** [CP_SaveGame](../WOLFSRC/WL_MENU.C#L70); [DrawLSAction](../WOLFSRC/WL_MENU.C#L1343) +- **Timing:** Acknowledge error; no gameplay advance. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** Native readable error in save panel. +- **Sound/music:** Menu effects; loading restores level music. +- **Input/state:** Keep prior slot and active game; retry/cancel supported. +- **Revive:** [HandleSaveMenu](../src/engine/WL_SAVE_MENU.c#L73) +- **Regression evidence:** [save](#save). Open findings: storage. + +### Quit + +#### window-close: gameplay → exit + +**Trigger:** SDL quit/window close **Status:** `partial`. + +- **DOS source:** [Quit](../WOLFSRC/WL_MAIN.C#L65) +- **Timing:** Immediate normal application teardown; no confirmation. +- **Palette:** Original gamepal indices; VGA-style DAC interpolation where faded. +- **Artwork/layout:** No additional screen. +- **Sound/music:** Stop music and sound before fade. +- **Input/state:** OS close exits directly from every presentation state. +- **Revive:** [DemoLoopPrepareExit](../src/engine/WL_MAIN.c#L51) +- **Regression evidence:** [classic](#classic). Open findings: hardware. + +## Evidence register + +### loading + +**Scope:** Actual frontend phases, partial page counts, palette steps, fresh ack, progression/secret routing/load and stable Enhanced geometry. + +[static void Loading](../tests/loading_tests.c#L59) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** Native source/artwork oracle; DOS execution now compares controlled progress drawings, not cache duration or the continuous loading sequence. + +### death + +**Scope:** 320 attacker/view scenarios, sentinel, rotation, tie/wrap, sound event, intermediate red fizzle and restart. + +[static void Death](../tests/loading_tests.c#L139) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** Source-derived native assertions, not executed-DOS death frames or physical audio latency. + +### classic + +**Scope:** F1–F10, pause, replacement confirmation, quick operations, clock/RNG freeze and final death. + +[static void Keys](../tests/classic_tests.c#L75) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** No continuous executed-DOS menu journey or enabled-DOS audio comparison. + +### interface + +**Scope:** DOS mouse thresholds/priority/buttons, separate relative menu capture, focus/enable release and regain, idle stability, keyboard input, music pause and disk phases. + +[static void Interface](../tests/classic_tests.c#L188) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** Native operation phases replace DOS disk serialization timing. + +### scores + +**Scope:** Qualification/ties, editing, cancellation, persistence and corrupt-file protection. + +[static void Scores](../tests/classic_tests.c#L270) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** No executed-DOS score-entry animation comparison; native file format. + +### hidden + +**Scope:** MLI/BAT, portable debug tools and all three jukebox banks. + +[static void Hidden](../tests/classic_tests.c#L232) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** No ISA/gameport/EMS/XMS debug emulation. + +### dos-pixels + +**Scope:** 30 full executed-DOS indexed frames: quit, disk, controlled Get Psyched progress, Pause art new-game message and default high scores. + +[int main](../tests/dos_ui_reference.c#L18) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** Controlled original drawing calls on a menu background, plus the original score table drawing; not gameplay composites, fades, sound, cache reads, input waits or animated name entry. + +### demo + +**Scope:** Four recordings, 5386 per-command DOS state hashes, Classic and Enhanced. + +[def owned_frames](../tests/test_demo_sync.py#L91) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** Reference archive revision, view size 15 and DOS sound off only; not every gameplay branch. + +### campaign + +**Scope:** Exit routing, secret return, inventory and restart. + +[static void TestProgression](../tests/campaign_tests.c#L61) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** Controlled fixtures and all-map loading, not human playthrough of all 60 floors. + +### finale + +**Scope:** Boss/BJ victory, statistics, articles and restarts. + +[static void TestRestartAndArticles](../tests/finale_tests.c#L270) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** Source-based native coverage; no continuous executed-DOS finale comparison. + +### signon + +**Scope:** Optional owned sign-on, capability lights, prompt and startup order. + +[class](../tests/test_signon.py#L21) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** Native capabilities replace DOS memory/card detection; no physical VGA timing. + +### save + +**Scope:** Persistence, CRC/field validation, failed writes, restart and deterministic continuation. + +[class](../tests/test_save.py#L13) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** Six native slots/version 1, not original ten-slot serialization. + +### audio + +**Scope:** IMF/OPL/PCM schedules, priorities, volumes, disabled effects/music and lifecycle. + +[static void Timing](../tests/audio_tests.c#L26) + +**Observed:** Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md. + +**Does not establish:** Emulated OPL with native gain; no calibrated physical DAC/OPL comparison. + +## Native UI coverage + +| State | Classification | Rows | Boundary | +| --- | --- | --- | --- | +| `UI_BOSS` | DOS-route | panel-boss, return-boss, game-boss, boss-game | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_CONFIRM` | DOS-route | quit-menu, quit-game, quit-no, quit-yes, quit-no-game | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_CONTROLS` | native-adaptation | panel-controls, return-controls, panel-display, return-display, game-controls, controls-game | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_CREDITS` | DOS-route | title-credits, credits-scores, credits-menu | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_DEMO` | DOS-route | scores-demo, demo-title, demo-menu | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_DIFFICULTY` | DOS-route | episode-difficulty, replace-yes, difficulty-setup, difficulty-back | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_DISK` | DOS-route | quicksave, quickload-yes, quick-resume, storage-error | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_DISPLAY` | native-adaptation | panel-display, return-display | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_DONE` | DOS-route | quit-yes, window-close | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_EPISODE` | DOS-route | menu-episode, episode-difficulty, episode-replace, episode-back, difficulty-back | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_ERROR` | native-adaptation | asset-error, error-menu, preload-error | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_GAME` | DOS-route | difficulty-setup, setup-psyched, psyched-progress, psyched-reveal, reveal-game, game-pause, pause-game, game-menu, menu-game, save-panel, load-panel, ordinary-load-setup, save-return, quicksave, quickload-confirm, quickload-no, quick-resume, message-return, death-turn, death-fizzle, death-ack, death-restart, restart-reveal, death-final, exit-completion, secret-completion, next-setup, secret-entry, secret-return, boss-victory, victory-stats, victory-article, article-scores, quit-game, debug-warp, warp-setup, cheat-message, asset-error, game-sound, sound-game, game-controls, controls-game, game-view, view-game, game-boss, boss-game, save-cancel-game, load-cancel-game, quit-no-game, end-game, end-yes, end-no, preload-error, window-close | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_HIGHSCORES` | DOS-route | credits-scores, scores-demo, attract-scores-menu | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_JUKEBOX` | DOS-route | jukebox, jukebox-return | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_LOAD` | DOS-route | load-panel, menu-load, load-work, load-cancel, load-cancel-game | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_MENU` | DOS-route | title-menu, credits-menu, attract-scores-menu, demo-menu, menu-episode, replace-no, episode-back, game-menu, menu-game, menu-save, menu-load, save-cancel, load-cancel, quit-menu, quit-no, panel-sound, return-sound, panel-controls, return-controls, panel-view, return-view, panel-boss, return-boss, error-menu, menu-scores, scores-menu, menu-attract, end-menu, end-no-menu | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_MESSAGE` | DOS-route | storage-error, message-return, cheat-message | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_PAUSE` | DOS-route | game-pause, pause-game | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_QUICK` | DOS-route | episode-replace, replace-yes, replace-no, quickload-confirm, quickload-yes, quickload-no, quit-menu, quit-game, quit-no, quit-yes, quit-no-game, end-game, end-menu, end-yes, end-no, end-no-menu | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_RATING` | DOS-route | signon-ack, rating-title | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_RESULTS` | DOS-route | death-final, article-scores, qualify, not-qualified, name-save, results-title | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_SAVE` | DOS-route | save-panel, menu-save, save-work, save-cancel, save-cancel-game, save-error | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_SCORES` | DOS-route | menu-scores, scores-menu | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_SIGNON` | DOS-route | startup, signon-ack, jukebox | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_SOUND` | DOS-route | panel-sound, return-sound, game-sound, sound-game | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_TITLE` | DOS-route | rating-title, title-credits, demo-title, title-menu, name-save, results-title, jukebox-return, menu-attract | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_VIEW` | DOS-route | panel-view, return-view, game-view, view-game | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | +| `UI_WARP` | DOS-route | debug-warp, warp-setup | Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates. | + +## DOS playstate coverage + +| State | Classification | Rows | Boundary | +| --- | --- | --- | --- | +| `ex_stillplaying` | route | game-pause, game-menu | Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case. | +| `ex_completed` | route | exit-completion, next-setup | Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case. | +| `ex_died` | route | death-turn, death-final | Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case. | +| `ex_warped` | route | warp-setup | Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case. | +| `ex_resetgame` | declaration-only | declaration only | Declared but not handled as a distinct GOODTIMES GameLoop route. | +| `ex_loadedgame` | route | ordinary-load-setup | Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case. | +| `ex_victorious` | route | boss-victory, victory-stats | Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case. | +| `ex_abort` | route | demo-menu, ordinary-load-setup | Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case. | +| `ex_demodone` | route | demo-title | Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case. | +| `ex_secretlevel` | route | secret-completion, secret-entry, secret-return | Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case. | + +## Excluded editions, hardware and native adaptations + +- GOODTIMES registered WL6 only: no shareware locks, SPEAR/JAPAN/SPANISH layouts or non-GOODTIMES help remapping. +- Original software raycaster and fixed-point 70 Hz rules remain shared by Classic and Enhanced. Modern controls, interpolation, six native saves, settings/score formats and volume controls are intentional adaptations. +- Physical DOS CRT/DAC/OPL, native Windows/macOS, WebAssembly and Android are not certified. Dummy SDL/Wine tests establish only their stated scope. No Android controls are introduced. + +## Keeping this inventory current + +The JSON manifest is authoritative for this document. After reviewing changed source/behaviour, update the records and evidence, then run: + +```sh +python3 scripts/audit_transitions.py --write +python3 scripts/audit_transitions.py --check +``` + +The check rejects missing fields, stale source hashes/anchors, unknown evidence/gaps, disconnected journeys, unclassified native UI states, and unclassified DOS exit values. It also checks that this document matches the manifest. It does **not** execute the game, discover arbitrary new branch conditions, or prove that a cited test asserts every property in its row. + +For a behaviour change, add an edge-specific regression before changing its evidence status. Record the initial/intermediate/final framebuffer, palette, time, sound events, input release/ack, map/lives/save/RNG and SDL window/logical geometry where applicable. A successful endpoint or a helper that drains loading is insufficient evidence for the presentation between endpoints. diff --git a/docs/GIT-SAFETY.md b/docs/GIT-SAFETY.md new file mode 100644 index 00000000..2d4b2b58 --- /dev/null +++ b/docs/GIT-SAFETY.md @@ -0,0 +1,38 @@ +# Repository safeguards + +Inspected on 2026-11-01 before source changes: clean `master` at `0516778`, +tracking `origin/master`. `origin` already pointed to +`https://github.com/raygibbon/wolf3d-revive.git`. No existing remote URL, +branch, commit or hook was replaced. CART's working tree was also clean. + +Local configuration now has: + +| Setting | Value | +| --- | --- | +| origin fetch/push | `https://github.com/raygibbon/wolf3d-revive.git` | +| upstream fetch | `https://github.com/id-Software/wolf3d.git` | +| upstream push | `https://invalid.invalid/upstream-push-disabled` | +| remote.pushDefault | `origin` | +| push.default | `simple` | +| core.hooksPath | `.githooks` | + +The executable `.githooks/pre-push` rejects destinations referencing +`id-Software/wolf3d`, ignoring case, including HTTPS, SCP-style SSH and +`ssh://` URLs. It checks both Git hook arguments and all effective push URLs +of a named remote, including URL rewrites. Tests invoke the hook directly in +temporary repositories. No push, commit, upstream fetch, or PR was performed. + +Verify locally without network activity: + +```sh +git remote -v +git config --local --get remote.pushDefault +git config --local --get push.default +git config --local --get core.hooksPath +python3 -m unittest discover -s tests -v +``` + +Git config is repository-local and is not transported by cloning. Future +checkouts must inspect their existing remotes and hooks before applying these +settings. Hooks can be deliberately bypassed; this guard prevents accidents, +and is not server-side access control. No pushes are part of this task. diff --git a/docs/HISTORICAL_README.rst b/docs/HISTORICAL_README.rst new file mode 100644 index 00000000..a161f91b --- /dev/null +++ b/docs/HISTORICAL_README.rst @@ -0,0 +1,218 @@ +Wolfenstein 3D +============== + +The original source release was made using the ``DEICE.EXE`` +installer (DeIce) in the root directory. (Basically a way to +split self-extracting zip files over multiple floppy disks.) +After execution, that installer will create the contents of +the ``WOLFSRC`` directory. In the "installed" directory, the +the ``README.TXT``, ``RELEASE.TXT``, and ``LICENCE.DOC`` reside +in the ``README`` directory. They are duplicated below. + +Travis "Ash" Bradshaw + +February 6, 2012 + +RELEASE.TXT +----------- + +:: + + We are releasing this code for the entertainment of the + user community. We don't guarentee that anything even + builds in here. Projects just seem to rot when you leave + them alone for long periods of time. + + This is all the source we have relating to the original + PC wolfenstein 3D project. We haven't looked at this + stuff in years, and I would probably be horribly embarassed + to dig through my old code, so please don't ask any questions + about it. The original project was built in borland c++ 3.0. + I think some minor changes were required for later versions. + + You will need the data from a released version of wolf or spear + to use the exe built from this code. You can just use a + shareware version if you are really cheap. + + + Some coding comments in retrospect: + + The ray casting refresh architecture is still reasonably + appropriate for the game. A BSP based texture mapper could + go faster, but ray casting was a lot simpler to do at the time. + + The dynamically compiled scaling routines are now a Bad Thing. + On uncached machines (the original target) they are the fastest + possible way to scale walls, but on modern processors you just + wind up thrashing the code cash and wrecking performance. + A simple looping texture mapper would be faster on 486+ machines. + + The whole page manager caching scheme is unecessarily complex. + + Way too many #ifdefs in the code! + + + Some project ideas with this code: + + Add new monsters or weapons. + + Add taller walls and vertical motion. This should only be + done if the texture mapper is rewritten. + + Convert to a 32 bit compiler. This would be a fair amount + of work, but I would hate to even mess with crusty old 16 + bit code. The code would get a LOT smaller. + + Make a multi-player game that runs on DOOM sersetup / ipxsetup drivers. + + + Have fun... + + John Carmack + Technical Director + Id Software + +README.TXT +---------- + +NOTES: + +This version will compile under BORLAND C++ 3.0/3.1 and compiled perfectly +before it was uploaded. + +Please do not send your questions to id Software. + +LICENCE.DOC +----------- + + :: + LIMITED USE SOFTWARE LICENSE AGREEMENT + + This Limited Use Software License Agreement (the "Agreement") + is a legal agreement between you, the end-user, and Id Software, Inc. + ("ID"). By continuing the downloading of this Wolfenstein 3D + (the "Trademark") software material, which includes source code + (the "Source Code"), artwork data, music and software tools + (collectively, the "Software"), you are agreeing to be bound by the + terms of this Agreement. If you do not agree to the terms of this + Agreement, promptly destroy the Software you may have downloaded. + + ID SOFTWARE LICENSE + + Grant of License. ID grants to you the right to use one (1) + copy of the Software on a single computer. You have no ownership or + proprietary rights in or to the Software, or the Trademark. For purposes + of this section, "use" means loading the Software into RAM, as well as + installation on a hard disk or other storage device. The Software, + together with any archive copy thereof, shall be destroyed when no longer + used in accordance with this Agreement, or when the right to use the + Software is terminated. You agree that the Software will not be shipped, + transferred or exported into any country in violation of the U.S. + Export Administration Act (or any other law governing such matters) and + that you will not utilize, in any other manner, the Software in violation + of any applicable law. + + Permitted Uses. For educational purposes only, you, the end-user, + may use portions of the Source Code, such as particular routines, to + develop your own software, but may not duplicate the Source Code, except + as noted in paragraph 4. The limited right referenced in the preceding + sentence is hereinafter referred to as "Educational Use." By so exercising + the Educational Use right you shall not obtain any ownership, copyright, + proprietary or other interest in or to the Source Code, or any portion of + the Source Code. You may dispose of your own software in your sole + discretion. With the exception of the Educational Use right, you may not + otherwise use the Software, or an portion of the Software, which includes + the Source Code, for commercial gain. + + Prohibited Uses: Under no circumstances shall you, the end-user, + be permitted, allowed or authorized to commercially exploit the Software. + Neither you nor anyone at your direction shall do any of the following acts + with regard to the Software, or any portion thereof: + + Rent; + + Sell; + + Lease; + + Offer on a pay-per-play basis; + + Distribute for money or any other consideration; or + + In any other manner and through any medium whatsoever commercially + exploit or use for any commercial purpose. + + Notwithstanding the foregoing prohibitions, you may commercially exploit the + software you develop by exercising the Educational Use right, referenced in + paragraph 2. hereinabove. + + Copyright. The Software and all copyrights related thereto + (including all characters and other images generated by the Software + or depicted in the Software) are owned by ID and is protected by + United States copyright laws and international treaty provisions. + Id shall retain exclusive ownership and copyright in and to the Software + and all portions of the Software and you shall have no ownership or other + proprietary interest in such materials. You must treat the Software like + any other copyrighted material, except that you may either (a) make one + copy of the Software solely for back-up or archival purposes, or (b) + transfer the Software to a single hard disk provided you keep the original + solely for back-up or archival purposes. You may not otherwise reproduce, + copy or disclose to others, in whole or in any part, the Software. You + may not copy the written materials accompanying the Software. You agree + to use your best efforts to see that any user of the Software licensed + hereunder complies with this Agreement. + + NO WARRANTIES. ID DISCLAIMS ALL WARRANTIES, BOTH EXPRESS IMPLIED, + INCLUDING BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS FOR A PARTICULAR PURPOSE WITH RESPECT TO THE SOFTWARE. THIS LIMITED + WARRANTY GIVES YOU SPECIFIC LEGAL RIGHTS. YOU MAY HAVE OTHER RIGHTS WHICH + VARY FROM JURISDICTION TO JURISDICTION. ID DOES NOT WARRANT THAT THE + OPERATION OF THE SOFTWARE WILL BE UNINTERRUPTED, ERROR FREE OR MEET YOUR + SPECIFIC REQUIREMENTS. THE WARRANTY SET FORTH ABOVE IS IN LIEU OF ALL OTHER + EXPRESS WARRANTIES WHETHER ORAL OR WRITTEN. THE AGENTS, EMPLOYEES, + DISTRIBUTORS, AND DEALERS OF ID ARE NOT AUTHORIZED TO MAKE MODIFICATIONS TO + THIS WARRANTY, OR ADDITIONAL WARRANTIES ON BEHALF OF ID. + + Exclusive Remedies. The Software is being offered to you free of any + charge. You agree that you have no remedy against ID, its affiliates, + contractors, suppliers, and agents for loss or damage caused by any defect + or failure in the Software regardless of the form of action, whether in + contract, tort, includinegligence, strict liability or otherwise, with + regard to the Software. This Agreement shall be construed in accordance + with and governed by the laws of the State of Texas. Copyright and other + proprietary matters will be governed by United States laws and international + treaties. IN ANY CASE, ID SHALL NOT BE LIABLE FOR LOSS OF DATA, LOSS OF + PROFITS, LOST SAVINGS, SPECIAL, INCIDENTAL, CONSEQUENTIAL, INDIRECT OR OTHER + SIMILAR DAMAGES ARISING FROM BREACH OF WARRANTY, BREACH OF CONTRACT, + NEGLIGENCE, OR OTHER LEGAL THEORY EVEN IF ID OR ITS AGENT HAS BEEN ADVISED + OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY. + Some jurisdictions do not allow the exclusion or limitation of incidental or + consequential damages, so the above limitation or exclusion may not apply to + you. + + General Provisions. Neither this Agreement nor any part or portion + hereof shall be assigned, sublicensed or otherwise transferred by you. + Should any provision of this Agreement be held to be void, invalid, + unenforceable or illegal by a court, the validity and enforceability of the + other provisions shall not be affected thereby. If any provision is + determined to be unenforceable, you agree to a modification of such + provision to provide for enforcement of the provision's intent, to the + extent permitted by applicable law. Failure of a party to enforce any + provision of this Agreement shall not constitute or be construed as a + waiver of such provision or of the right to enforce such provision. If + you fail to comply with any terms of this Agreement, YOUR LICENSE IS + AUTOMATICALLY TERMINATED and you agree to the issuance of an injunction + against you in favor of Id. You agree that Id shall not have to post + bond or other security to obtain an injunction against you to prohibit + you from violating Id's rights. + + YOU ACKNOWLEDGE THAT YOU HAVE READ THIS AGREEMENT, THAT YOU + UNDERSTAND THIS AGREEMENT, AND UNDERSTAND THAT BY CONTINUING THE + DOWNLOADING OF THE SOFTWARE, YOU AGREE TO BE BOUND BY THIS AGREEMENT'S + TERMS AND CONDITIONS. YOU FURTHER AGREE THAT, EXCEPT FOR WRITTEN SEPARATE + AGREEMENTS BETWEEN ID AND YOU, THIS AGREEMENT IS A COMPLETE AND EXCLUSIVE + STATEMENT OF THE RIGHTS AND LIABILITIES OF THE PARTIES. THIS AGREEMENT + SUPERSEDES ALL PRIOR ORAL AGREEMENTS, PROPOSALS OR UNDERSTANDINGS, AND + ANY OTHER COMMUNICATIONS BETWEEN ID AND YOU RELATING TO THE SUBJECT MATTER + OF THIS AGREEMENT + diff --git a/docs/LICENSING.md b/docs/LICENSING.md new file mode 100644 index 00000000..bc3ee558 --- /dev/null +++ b/docs/LICENSING.md @@ -0,0 +1,39 @@ +# Source licensing and provenance + +The original release's limited-use notice remains untouched in +`WOLFSRC/README/LICENSE.DOC` and the historical `README.rst`. Preserve its +copyright notices and the original snapshot in Git history. + +The historical GPL relicensing basis is John Carmack's account in id Software's +[official iDoom source-release README](https://github.com/id-Software/DOOM-IOS2/blob/master/readme_iDoom.txt). +It states that the original Wolfenstein source was initially noncommercial +and later released under the GPL. This project uses that later grant as its +basis for the active engine port; new C source in `src/` is GPL-2.0-only. +`COPYING` contains the GNU GPL version 2. This does not replace the historical +notice or purport to relicense archived DOS binaries, tools or artwork. + +Milestone 6B imports Mitsutaka Okazaki's +[emu8950](https://github.com/digital-sound-antiques/emu8950) directly from +commit `f82a22e80b68820f263084aa8506b12eb1c9b4dd`, under its +[MIT licence](../third_party/emu8950/LICENSE). Preserve that licence and its +copyright notices when distributing source or binaries. The active port stays +GPL-2.0-only; these imported files retain their MIT terms. Exact provenance +and two local safety patches are listed in +[README.wolf3d.md](../third_party/emu8950/README.wolf3d.md). +No code was copied from a third-party Wolfenstein port. Nuked-OPL3 was reviewed +but not imported. SDL3 uses the zlib licence; retain its notices when distributing +it. See [MILESTONE6B.md](MILESTONE6B.md) for dependency selection and limitations. + +Commercial `.WL6` files, SIGNON artwork, music, sounds, trademarks and other +game content are separate from the engine source license. Supply your own +Steam data outside this repository; never stage or distribute it. Milestone 2 +reads the user's local Steam data in place. No commercial archive was copied +into the source tree or downloaded. Local rendered captures remain ignored. + +`src/engine/gamepal.inc` reproduces the original 768-byte, six-bit VGA palette +from the already tracked `WOLFSRC/OBJ/GAMEPAL.OBJ` LEDATA record; it is not +extracted from Steam artwork. Tests independently parse that original OMF +record and check the generated constants. `GFXV_WL6.h` is the original generated +graphics-index header, copied with its DOS EOF marker removed. The original +objects and source files remain untouched. No SIGNON artwork or third-party +port implementation is incorporated in the active title path. diff --git a/docs/MILESTONE10_DOS_MENUS.md b/docs/MILESTONE10_DOS_MENUS.md new file mode 100644 index 00000000..e8aebf4a --- /dev/null +++ b/docs/MILESTONE10_DOS_MENUS.md @@ -0,0 +1,221 @@ +# Milestone 10: classic DOS menus and startup presentation + +Implemented and locally verified on 2026-11-03 (Australia/Adelaide). +The original menu artwork is loaded from owned WL6 archives at runtime. +No commercial graphics, captures or replacement artwork are committed. +The root README, original sources, save/configuration formats, control bindings, +70 Hz simulation, demo command timing and Milestone 9 world renderer are retained. + +## Original reference and verified assets + +Reviewed the unchanged original implementations: + +- `WOLFSRC/WL_MENU.C`: `DrawCtlScreen`, `DrawSoundMenu`, `DrawMenu`, + `DrawMenuGun`, `DrawMouseSens`, panel outlines and cursor timing. +- `WOLFSRC/WL_MENU.H`: Control and Sound coordinates and panel dimensions. +- `WOLFSRC/WL_INTER.C`: `PG13` composition and seven-second input wait. +- `WOLFSRC/WL_MAIN.C`: startup/sign-on and title/credits/scores/demo sequence. + +The owned Steam WL6 archive successfully decoded every control-panel picture +(slot 10 through 42), the title, credits, high-score heading and rating graphic. +The existing WL6/GOODTIMES picture mapping and main-menu edition layout remain +in use; no artwork or menu rows from other editions are fabricated. + +| Archive artwork | Size in source pixels | +| --- | --- | +| `C_CONTROLPIC` | 144×48 | +| `C_CUSTOMIZEPIC` | 152×48 | +| `C_CURSOR1PIC`, `C_CURSOR2PIC` | 24×16 each | +| `C_NOTSELECTEDPIC`, `C_SELECTEDPIC` | 24×8 each | +| Sound Effects, Digitized Sound, Music headings | 136×16 each | +| `C_MOUSELBACKPIC` instruction legend | 104×16 | +| `PG13PIC` (slot 88, artwork labelled **PC-13**) | 88×64 | +| Title and credits | 320×200 each | + +All palette indices and VGA palette expansion remain original. Validation uses +independent source-composition pixel oracles and locally inspected captures +from the owned archives. No independent DOS-emulator screenshot comparison is +claimed. + +## Control menu and modern options + +The first Control page follows the original source composition: + +- Red background, stripes at y=10, original heading at (80,0), instruction + legend at (112,184), dark-red panel at (16,65), size 284×84. +- Font 1 at x=80, y=70+13×row, original normal/highlight/disabled palette colours. +- Pistol at x=24, y=68+13×row; original toggle graphics at x=56, y=73+13×row. +- Original six labels: Mouse Enabled, Joystick Enabled, Use joystick port 2, + Gravis GamePad Enabled, Mouse Sensitivity and Customize controls. + +Unsupported joystick rows remain dark red and navigation skips them. Mouse +Sensitivity is disabled while the current profile's mouse is off. Its separate +DOS-styled slider retains Revive's existing 1..40 sensitivity range. + +Customize controls opens a subordinate page using the original Customize +heading, fonts, pistol and instruction legend. Classic/Modern preset selection, +per-profile mouse settings, inversion, defaults, key bindings and Display +settings remain available there. Binding capture, conflict detection, reserved +keys and alternate bindings retain their existing behaviour. Display retains +all existing functionality and now also uses a pistol selector and the original +legend. Returning from Display restores the Customize page rather than losing +the user's place at the root Control menu. + +The initial branch's cursor fix was validated, then extended to the restored +root/subordinate pages. Control and Sound share the existing tic-driven pistol +animation, including both archived frames, original greater-than-8 / +greater-than-70 tick blink thresholds and bounded coarse-clock catch-up. Moving +selection restores the first pistol frame. Held up/down navigation on the +Control, Customize and Sound pages repeats at the original 20-tick interval; +binding capture continues to consume physical keys without navigating. Menu move/select/back feedback uses +the existing original sounds without advancing gameplay or gameplay RNG. + +## Sound menu + +The original three headings and panel proportions are retained: + +| Section | Panel (x,y,width,height) | Heading draw position | +| --- | --- | --- | +| Sound Effects | (40,17,250,45) | (100,0) | +| Digitized Sound | (40,82,250,45) | (100,65) | +| Music | (40,147,250,32) | (100,130) | + +Buffered picture x positions retain the original eight-pixel alignment. +The original fonts, red/yellow toggle art, pistol and bottom legend are used. +The five selectable rows are Effects None, AdLib effects, Adjust volumes, +Music None and AdLib music. Volume adjustment opens a separate DOS-styled page +with the same existing 0..100%, five-point adjustment steps. + +Revive has one effects enable/volume pair covering synthesis and digitized +samples. Consequently, the digitized section reports its actual playback +status as **With sound effects**, with a toggle-status graphic and explanatory +text. It is a status panel, not a second device selector or newly persisted +mode. No PC speaker, Disney Sound Source or nonfunctional physical sound-device +options are offered. The existing `SD_DigitizedMode` behaviour is preserved. +Music/effects enables, volumes and both control profiles use the unchanged +configuration writer and schema. + +## Startup and attract sequence + +Normal application startup now shows the verified PC-13 artwork using the +original `PG13` composition: palette index 0x82 fills the 320×200 framebuffer, +and the 88×64 archived picture is drawn at (216,110). It fades in, waits seven +seconds in 70 Hz time, then fades to the title; a key skips the wait to the +title. The rating appears once at startup, not on every attract-loop cycle. +`--menu` and `--level` continue to enter their requested screens directly. + +An absent picture or nonmatching dimensions leaves the existing title startup +in place. A present but malformed graphic reports a loading error. There is no +substitute/generated commercial artwork. `CA_GrChunkPresent` provides a +non-mutating presence check so optional sparse graphics do not become mandatory. + +The original `SignonScreen` uses `introscn`, an image linked into the DOS +executable, rather than a WL6 graphics-archive picture. It is outside this +archive-backed restoration. No separate SETUP.EXE screen, device-detection +screen or executable-linked image is reconstructed. The existing title, +credits, high scores and four recorded demos retain their order and timings; +the rating runs as UI time without consuming simulation ticks or demo commands. + +## Fixed 4:3 presentation + +The existing SDL3 logical-presentation mechanism is retained. A shared +read-only predicate now excludes intermission and victory/end-text pages from +world presentation even while they remain inside `UI_GAME`; previously those +static pages inherited the enhanced world's logical canvas. Every menu, dialog, rating, title, credits and static interface +screen uses the **320×200 indexed framebuffer**, presented as **320×240 logical +pixels** with centred aspect-preserving letterboxing. Artwork coordinates +never depend on monitor width. + +On the native 1920×1200 panel, SDL reported a **1600×1200** menu rectangle at +**(160,0)**. Fullscreen X11/SDL OpenGL readbacks compared every physical output pixel for +Control, intermission, victory and end-text screens: original source pixels +occupy exactly 5×6 physical pixels each and both 160-pixel side borders are +opaque black. The actual full-output Control capture was inspected. Readback redraws before +capture because an accelerated backend's post-present back buffer is undefined. + +Synthetic tests cover 1920×1200, 1920×1080, 3440×1440 and 3840×1080 drawables, +black side borders, logical 320×240 dimensions, fullscreen/windowed changes, +menus entered during enhanced gameplay, and return to the configured 16:9 world. +The existing display suite also covers integer/Fit scaling, tiny +windows, filtering, display-setting failures and gameplay isolation. Enhanced +world presentation remains restricted to game/demo states; UI screens use fixed 4:3 presentation, including while a game is paused behind them. +No SDL texture, backend, shader or world-rendering policy was added. + +## Regression results + +| Check | Result | +| --- | --- | +| Strict GCC C11 `-O2`, pedantic/conversion/shadow warnings, `-Werror` | Full application and native diagnostics passed | +| CART `cart-sdl` build | Passed | +| Complete Linux suite, owned WL6 | **123 passed**, 461.671 s; no skips | +| Final ASan/UBSan verification, all 12 modules and instrumented app | **123 passed**, 358.230 s with four parallel processes; every process exited 0, no findings or skips | +| Final static-page/menu ASan/UBSan regressions after presentation correction | **3 passed**, 25.877 s | +| Final menu/input/sound regressions, including held repeat | **10 passed** normally (38.663 s) and **10 passed** under ASan/UBSan (75.430 s) | +| Focused display/menu regressions | **3 passed**, 15.167 s | +| Independent indexed-pixel Control, adapted Sound and rating composition | Exact reference-buffer comparisons passed | +| Original Classic framebuffer oracle | Exact reference hashes retained | +| Milestone 9 native renderer oracle | All **1,500** hashes retained | +| All four original DOS recordings | **5,386/5,386 commands match**, Classic and interpolated native paths, normal and sanitizers | +| Native 1920×1200 fullscreen Control/intermission/victory/end text | Every output pixel matches source DOS pixels at 5×6 physical pixels each; both 160-pixel borders black | +| MinGW x86_64 strict C11 full app and new menu harness | Passed, SDL3 3.4.18 SDK | +| Wine owned-data menu/persistence/rating/static-page/presentation tests | Passed | +| Final diff | Clean; README, WOLFSRC, simulation, frame clock, native world renderer and save/configuration implementations unchanged | + +The full normal suite was rerun after the static-page correction. The final +held-repeat adjustment was followed by the ten focused menu/input/sound tests +in both normal and sanitizer builds. No world-renderer, simulation or save-format +changes were needed. + +An earlier serial sanitizer log reported 123 tests and `OK`, but its command +wrapper returned termination status 143 when collected. For unambiguous final +results, all twelve test modules were rerun on the final presentation code in +four parallel child processes, recording each actual exit status. Every module +exited 0; `sanitizers-final/summary.json` records all 123 tests and no findings. +The subsequent held-repeat change is covered by the final ten-test sanitizer +run above. + +The new `tests/dos_menu_tests.c` independently decodes archived planar pictures +and original font glyphs into reference buffers. It compares all 64,000 indexed +pixels for the source-authentic Control composition, both pistol frames and +mouse-enabled/disabled states; the adapted Sound composition; and PC-13 artwork. +It also exercises disabled-row navigation, sensitivity/preset/inversion changes, +volume/enables and configuration round trips, missing or wrong-size optional +rating art, fine/coarse cursor timing, held-arrow repeat, input dismissal, paused-game save-payload +isolation and the 4:3-to-widescreen round trip. Synthetic fixtures contain solid +colours and generated glyph patterns, not copies of original artwork. + +Raw logs and all captures stay in ignored `build/checks/m10/`. Relevant logs: +`final-suite.log`, `sanitizers-final.log`, `sanitizers-final/*.json`, +`menu-input-final.log`, `menu-input-final-asan.log`, `static-pages-asan.log`, +`display.log`, `native-pages.log`, `wine-input-final.log` and `cart-final.log`. Capture inspection +includes main menu, Control on/off, Customize, Sound, Volume, title, credits, +PC-13 and a full-output native 1920×1200 Control menu. Commercial captures must +not be added to commits or PR attachments. + +## Reproduction + +```sh +export WOLF3D_DATA="$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" +export SDL_SDK=../cart/vendor/SDL +mkdir -p build/checks/m10 + +gcc -std=c11 -O2 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -Isrc -I"$SDL_SDK/include" src/main.c src/engine/*.c src/platform/*.c \ + "$SDL_SDK/build/libSDL3.a" -pthread -lm -o build/checks/m10/wolf3d-revive +WOLF3D_BINARY="$PWD/build/checks/m10/wolf3d-revive" \ + python3 -m unittest discover -s tests -v + +# Instrument the app as well as the harnesses; the SDL SDK is not instrumented. +gcc -std=c11 -O1 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -fsanitize=address,undefined -fno-omit-frame-pointer -g \ + -Isrc -I"$SDL_SDK/include" src/main.c src/engine/*.c src/platform/*.c \ + "$SDL_SDK/build/libSDL3.a" -pthread -lm -o build/checks/m10/wolf3d-revive-asan +SANITIZE=1 CC="gcc -O1" UBSAN_OPTIONS=halt_on_error=1 \ + WOLF3D_BINARY="$PWD/build/checks/m10/wolf3d-revive-asan" \ + python3 -m unittest discover -s tests -v +``` + +Physical Windows, ultrawide panels, high-DPI scaling and other fullscreen +compositors remain hardware checks. Wine and synthetic drawable dimensions +verify API behaviour rather than those physical environments. No new physical +audio-device measurements or complete campaign playthrough are claimed. diff --git a/docs/MILESTONE11_SIGNON.md b/docs/MILESTONE11_SIGNON.md new file mode 100644 index 00000000..a82d8b6d --- /dev/null +++ b/docs/MILESTONE11_SIGNON.md @@ -0,0 +1,236 @@ +# Milestone 11: original DOS sign-on + +**Branch:** `feature/11-dos-signon-screen` + +Normal startup can display the authentic DOS sign-on image with its id +Software, Wolfenstein 3D and Activision logos, red background and original +memory/hardware panel. No replacement artwork or commercial asset is added +to the repository. The optional image must come from an owned installation. + +## Supplying the artwork + +`SIGNON.RAW` belongs in the directory passed to `--data`. It is exactly +**64,000 bytes**: 320x200 row-major palette indices, top row first, with no +header, padding, compression or appended palette. It uses the game's original +256-colour VGA `gamepal` (768 six-bit channel values), already preserved by the +engine. Every byte is a pixel index; this is not planar VGA memory, RGB data, +a screenshot, a WL6 graphics chunk or a setup-program screen. + +The supported automatic extraction uses the owned Steam/Activision WL6 DOS +`wolf3d.exe` (108,779 bytes). Run from the repository root, with Python 3.9+: + +```sh +python3 scripts/extract_signon.py \ + "/path/to/owned/Wolfenstein 3D/base/wolf3d.exe" \ + "/path/to/owned/Wolfenstein 3D/base/SIGNON.RAW" +``` + +You can also pass the Steam install directory (or its `base` directory) +instead of the executable. To recover the image linked by the historical +Wolf source release: + +```sh +python3 scripts/extract_signon.py WOLFSRC /private/path/SIGNON.RAW +# Also accepts WOLFSRC/OBJ/SIGNON.OBJ or the repository root directly. +``` + +The extractor discovers recognised files in those directories, preferring a +supported Steam executable when available. This is an explicit local setup +step; the game itself still reads `SIGNON.RAW` and does not run Python at launch. +The source **C files alone do not contain the artwork**: the historical +`OBJ/SIGNON.OBJ` asset is required. That source-release image contains a different +publisher logo; use the Steam version for the Activision logo. The original +pixels are preserved for either version. + +The source object's SHA-256 is +`dd66c2a2c7744988ad7700c826674d6747859bde9baf817cba7399f99937b376`; +its recovered pixels hash to +`4fd711cdde7929645a46dd572ab61feacc8d3b79844250835b0ce87312a2c999`. +The tool reconstructs its OMF LEDATA records, checking record lengths, +checksums when present, segment bounds, overlapping data and complete coverage +of all 64,000 pixels. It never modifies the object or embeds its data in code. + +Alternatively extract into an existing private staging directory, then copy +`SIGNON.RAW` beside the WL6 archives. The output must be new: existing files +are never overwritten, and the original executable is never modified or run. +Output inside the source tree is restricted to ignored `build/`, `data/` or +`game-data/` directories. `SIGNON.RAW` is also ignored by Git. Do not force-add +artwork, commercial executables or captures. + +The tool verifies all three SHA-256 identities before writing: + +| Item | SHA-256 | +| --- | --- | +| Owned compressed DOS EXE | `48d9594649f330956e86ea1892bab76b2d83cfd4038e262ff8f3383ba945ec09` | +| Decompressed MZ load image, 254,014 bytes | `d397db84048d18bbb90df0ba0db88bdf5982ce3cac868bec13f117e61fb74ff0` | +| Original 320x200 pixels | `d3c2f25b82b24f3513be29ee12bd5dc71ab1b0ac737d5111cbd36150927fa6f7` | + +For that exact executable, the pixels begin at load-image offset `0x23760`. +The bounded decoder handles the executable's LZEXE stream in Python, without +external programs. It checks input bounds, output size, backwards references +and checksums. Unknown or modified executable revisions are rejected rather +than searched heuristically. This decoder only recovers the load image; it +does not reconstruct an executable or relocation table. + +The LZEXE format was checked against [Fabrice Bellard's original +reference](https://bellard.org/lzexe/) and independently decoded using +[UNLZEXE](https://github.com/mywave82/unlzexe). The owned executable has a +modified startup stub that the unmodified UNLZEXE signature check rejects; +a private reference copy accepted its verified LZ91 header. Both decoders +produced identical load-image bytes. No third-party decompressor source is +bundled. The owned load image also contains the exact original VGA palette +used by Revive. + +### Other revisions: supported manual import + +Automatic profiles cover the checksum-listed Steam executable and source object. Other releases +can supply the same RAW format if their original linked image can be identified +reliably. Publisher logos can differ; do not substitute newly drawn artwork. + +For an **uncompressed DOS MZ executable with its matching linker MAP**: + +1. Locate the `_signon` (or `introscn`) symbol and its 64,000-byte segment in + that exact build's MAP. Do not apply addresses from another revision. +2. Read the EXE header size: the little-endian word at file offset `0x08`, + multiplied by 16. The map's `segment:offset` address is relative to the MZ + load image. File position is `header_size + segment*16 + offset`. +3. Copy exactly 64,000 bytes at that position into a new `SIGNON.RAW`. Check + that the entire range lies within the executable's declared MZ image, + excluding any appended debug data. The source build must use the same VGA + palette. Do not deinterleave or flip the pixels. +4. If the executable is packed, first unpack it with a tool supporting that + packer/revision. Re-read the resulting MZ header size and use the matching + original load-image map. A screen capture cannot reliably recover palette + indices or the untouched linked image. + +Without a matching map, object module or verified extraction profile, this +manual route cannot identify an arbitrary executable safely. Leave the optional +artwork absent rather than guessing offsets. The game still starts normally. + +## Historical implementation and compatibility + +`WOLFSRC/ID_HEADS.H` aliases `introscn` to the far symbol `signon`. +`WOLF3D.PRJ` links `OBJ/SIGNON.OBJ`; the historical linker MAP identifies +`SIGNON.BIN` in the 64,000-byte `SignonSeg` FAR_DATA segment. The image was +converted to an OMF object and linked into the executable, separately from the +WL6 graphics archives. `SignonScreen()` sets `gamepal`, calls `VL_MungePic()` +on the row-major image to convert it for DOS VGA planes, copies it to screen, +then releases its original storage. Revive copies the original row-major bytes +directly into the existing indexed framebuffer. `WOLFSRC/` is unchanged. + +DOS startup order was sign-on → subsystem initialization → `IntroScreen()` +memory/card fills → `FinishSignon()` acknowledgement → attract startup, +including the optional PG13 rating and title sequence. Revive loads the +resources needed for its original font first, then presents: + +**Sign-on → keypress → optional PG13 rating → title → existing attract loop.** + +- `FinishSignon()` clears `(0,189,300,11)` with the original top-left background + index, centres font 0 at y=190 and draws **Press a key** in palette index 14 + (yellow). On acknowledgement it draws **Working...** in index 10 (green). + The rest of the linked image, including the publisher logos, is untouched. +- The original unfilled Main/EMS/XMS bars and Mouse/Joystick/AdLib/Sound + Blaster/Sound Source boxes are preserved. They are **not measurements** or + failed detection results. Revive does not claim to detect DOS conventional, + EMS/XMS memory or ISA cards, and does not fill them with invented numbers. + This deliberately retains the untouched artwork instead of simulating a + DOS hardware inventory. Modern controls and audio remain available normally. +- Sign-on waits indefinitely for fresh acknowledgement input. Input already + pending when it opens is cleared. The dismissal key, held-key repeats, + keyboard text and mouse acknowledgement do not leak to the next page. +- The sign-on uses the existing palette fade-in. Its dismissal fades to black, + followed by the existing rating/title fade and a fresh page deadline. Music + is silent during sign-on and the existing intro track resumes afterwards. +- `--menu` and `--level` bypass this historical startup. Sign-on is never + inserted into in-game menu transitions or repeated by the attract loop. +- Missing optional artwork is skipped. Wrong lengths/read errors produce a + clear diagnostic; invalid input never partially replaces the framebuffer. + The application reports malformed supplied artwork as a startup error. + +## Presentation + +The existing SDL3 presentation path treats `UI_SIGNON` as DOS interface content, +never an enhanced world. The framebuffer stays 320x200; the logical canvas is +320x240, correcting DOS VGA pixel aspect to 4:3. Fit/Integer scaling uses the +existing menu preference, with black unused output and no SDL window resize. + +Fit examples, allowing SDL's final pixel rounding: + +| Window / output | Centred artwork | +| --- | --- | +| 1920x1200 | 1600x1200, 160-pixel side borders | +| 1920x1080 | 1440x1080, 240-pixel side borders | +| 1280x800 | approximately 1067x800 | +| 3440x1440 | 1920x1440 | +| 3840x1080 | 1440x1080 | + +No gameplay renderer, fixed 70 Hz simulation, RNG, demo decoding, HUD or +Milestone 9 performance code was changed. + +## Validation + +All checks used strict C11 with `-Wall -Wextra -Wpedantic -Wconversion +-Wshadow -Werror` (GCC 14.2). Both the application and SDL harness compiled. + +| Check | Result | +| --- | --- | +| Full existing suite plus new sign-on tests, owned WL6 available | 136 passed, no skips (547.585 s) | +| Full ASan/UBSan suite, application and test binaries instrumented | 136 passed across 13 modules, no skips or findings (518.173 s) | +| Focused extraction/sign-on suite | 13 passed normally and under sanitizers | +| Original DOS demos, classic and enhanced | All four traces / 5386 commands unchanged | +| DOS menu pixel comparisons, rendering hashes, controls, save/load | Passed | +| Strict Linux / MinGW and CART SDL builds | Passed | +| Native Linux and Windows executable under Wine | Passed within the display limits below | + +The normal suite used: + +```sh +WOLF3D_BINARY="$PWD/build/checks/m11/wolf3d-revive" \ +WOLF3D_DATA="/path/to/owned/WL6" CC='gcc -O1' \ +python3 -m unittest discover -s tests -v +``` + +Sanitizer modules ran in four independent subprocesses using `SANITIZE=1`, +`CC='gcc -O1'`, `UBSAN_OPTIONS=halt_on_error=1` and an ASan/UBSan application +binary. Every module exit status and log was checked. Full suite logs, private +artwork and native/Wine captures are under ignored `build/checks/m11/`. + +The later Python-only source-object/directory extraction update passed all +16 focused extraction/sign-on tests normally (11.609 s) and with the sanitizer +harness/application (22.719 s), without skips or findings. These include source +object recovery, directory detection and malformed OMF records. The full-suite +counts above describe the completed milestone validation before that follow-up; +the game engine and presentation code did not change in the follow-up. + +Focused checks cover extraction identities and output protection, invented +LZEXE token streams, malformed references and bounds, valid/missing/truncated/ +oversized RAW images, original font composition, palette accuracy, silent +sign-on, prompt interaction, held-key isolation, rating/title ordering, +`--menu`/`--level` bypass, all listed aspect geometries, black output borders, +zero window resize events and unchanged timing/RNG. + +Native Linux SDL3 X11/OpenGL validation on a physical 1920x1200 panel passed: +every output pixel matched the owned indexed image at 5x6 texels, with exactly +160 black pixels on each side. The captured original-art layout was visually +inspected. Dismissal preserved window dimensions and emitted no resize events. +Strict Linux and MinGW builds, CART's SDL build and the Windows test executable +under Wine also passed. Wine used SDL 3.4.18 dummy/software rendering; Linux +used the local SDL 3.5.0 development SDK. + +Physical ultrawide, high-DPI/mixed-DPI, multi-monitor and native Windows display +testing were unavailable. Exact widescreen and ultrawide geometries are covered +by SDL dummy/software tests; Wine does not establish physical Windows display +behaviour. Extraction was verified against the owned Steam/Activision executable and +the historical source object listed above; other publisher/release executables +require manual import or a future separately verified profile. Commercial art, diagnostics and captures +remain in private temporary or ignored build directories. + +## Milestone 12 capability overlays + +The later fidelity branch fills the original Mouse, AdLib-only and Sound +Blaster boxes when the front end reports an SDL mouse, loaded synthesis or +loaded digitized playback respectively. Positions/colors follow `IntroScreen`. +These indicate supported runtime equivalents, not detection of physical ISA +hardware. Memory/EMS/XMS, joystick and Sound Source remain unfilled. The +untouched-artwork validation above describes Milestone 11; current sign-on +regressions include these explicit, bounded overlays. diff --git a/docs/MILESTONE12_DOS_FIDELITY_BACKLOG.md b/docs/MILESTONE12_DOS_FIDELITY_BACKLOG.md new file mode 100644 index 00000000..f1d08f6c --- /dev/null +++ b/docs/MILESTONE12_DOS_FIDELITY_BACKLOG.md @@ -0,0 +1,364 @@ +# Milestone 12: DOS fidelity completion + +Branch: `feature/12-dos-fidelity-completion`. The requested checklist was absent +from the starting branch; this document reconstructs its batches from the task. +Historical `WOLFSRC/` is read-only. Checks below distinguish implementation, +regression verification and physical DOS comparison. + +## Batch A — personality and menus + +- [x] Nine quit sayings and DOS selection behavior (`WL_MENU.C endStrings`, + `CP_Quit`, `CP_CheckQuick` → `MenuQuitMessage`, `QuickDialog`). Verified by synthetic and owned-data Classic regressions. Preserve C precedence `a & (7 + (b & 1))`. Separate + UI entropy intentionally protects gameplay/demo RNG order. +- [x] Confirmation cursor, Y/N/Escape, answer-release wait and sound + (`Confirm` → `BeginConfirmation`/`HandleConfirmation`). Shared main/quick/new + dialogs verified; save overwrite uses the same implementation in Batch D. +- [x] Original Pause picture at (128,64), music off/on, input clearing and clock + freeze (`WL_PLAY.C CheckKeys` → `UI_PAUSE`). Verified by synthetic and owned-data Classic regressions. +- [x] New-game confirmation after episode selection, before skill selection + (`CP_NewGame`, `CURGAME` → `QUICK_NEW`). Declining returns to the main menu; + quick-save selection resets only after accepting a difficulty. Verified by synthetic and owned-data Classic regressions. +- [x] Menu transitions/audio: original dark-red fades and movement/select/ + Escape sounds retained. `CP_Quit`/`CP_CheckQuick` silence music and effects + before fading out; focused regression verifies both streams stop. Exhaustive + physical DOS audio comparison is separately pending in Batch E. + +## Batch B — high scores and completion + +- [x] DOS seven-entry defaults, strict score/floor tie qualification and episode + display (`ID_US_1.C Scores`, `WL_INTER.C CheckHighScore/DrawHighScores` → + `WL_HIGHSCORES.c`, `WL_INTER.c`). Exact ties preserve existing ordering. +- [x] Editable names with original 57-character/100-pixel pre-insertion limits, + I-bar cursor, arrows/Home/End/Backspace/Delete, Enter accepts, Escape retains + the inserted blank name (`US_LineInput` → `HandleHighScoreEntry`). +- [x] Portable atomic `highscores.w3h` persistence, independent of saves/config. + Seven explicit little-endian records, version/count and checksum validation. + Invalid/future files are preserved; write errors keep session rankings and + show a readable message. No DOS CONFIG.WL6 import. +- [x] Final death and victory → original 30-tic black fades → qualification → + name entry or 500-tic wait → title/attract (`WL_GAME.C GameLoop` → `UI_RESULTS`). Historical source has + **no separate Game Over card** in these paths; do not invent one. +- [x] Explicit End Game sets zero lives and enters the existing death sequence, + then qualifies the score (`CP_EndGame` → `QUICK_END`). + +Verification: strict application compilation passed. `test_classic.py`: all +nine synthetic/owned tests passed (34.935 s), including a second process reading +persisted rankings, exact ties, edit insertion, cancellation, corrupt-file +protection, final End Game path and unchanged RNG. Full engine/finale regression +validation is recorded in Batch E. Shifted punctuation and native editor +repeat support are covered in Batch D. + +## Batch C — startup and hidden features + +- [x] Sign-on device lights use `WL_MENU.C IntroScreen` coordinates/colors: + mouse (164,82), synthesis-only (164,128), digitized (164,151), 12×2, index 14. + Front end supplies actual SDL mouse / loaded audio capabilities. No invented + conventional/EMS/XMS sizes, joystick, Sound Source or physical ISA detection. + Those hardware-specific indicators remain intentionally unfilled. +- [x] Startup retains Milestone 11 artwork, FinishSignon prompt and rating/title + ordering; native DOS memory-manager startup order is not simulated. +- [x] Robert's Jukebox (`WL_MAIN.C DoJukebox` → `DemoLoopJukebox`): all 18 labels, + original track indices, three six-song banks, cursor, selection and Escape. + Held M at startup, M at sign-on, or `--jukebox` enters it. Portable bank choice + uses monotonic time instead of DOS hundredths; exit returns to title. +- [x] MLI and BAT (`WL_PLAY.C CheckKeys` → `HiddenKeys`): exact inventory, + zero score, +42000 tics, original text, paused acknowledgement/input isolation. +- [x] Portable debug scope audited: `--goobers`, original Backspace+LeftShift+Alt unlock, + Tab+G/H/I/E/F/C/P/Q/W/X implemented (god mode, hurt, items, end level, coordinates, + counts, picture pause, quit, episode-local warp and original placeholder). Damage bypass is false by default and isolated + from demos; it is session-only, preserving save format. Warp validates floors 1–10, preserves inventory and resets entry score, floor + counters and music through normal setup. The DOS page-cache shape/memory + viewers (EMS/XMS/address/last-hit fields), VGA border-register control and + simulation/VBL timing debuggers are not emulated; these hardware diagnostics + have no equivalent in the portable fixed-step engine. + +Verification: `test_classic.py` all 10 tests passed (44.546 s); `test_signon.py` +all 16 passed (13.197 s), strict C11. Coverage includes MLI penalty/RNG, BAT, +unlock, invulnerability/hurt, every jukebox bank, original sign-on pixels outside +supported overlays, prompt, input clearing and exact 4:3/widescreen geometry. +Physical DOS audio timing and non-WL6 edition layouts remain unverified. + +## Batch D — interface + +- [x] `DrawLSAction`/`DiskFlopAnim` → original Saving/Loading windows and both + disk pictures. Separate nonblocking start/work/finish phases for slot and + quick operations, no simulation/RNG advancement. Portable atomic I/O remains + synchronous within its work phase; disk-flip cadence follows those phases, + not DOS serialization-chunk timing. Six existing slots/save version retained. +- [x] Overwrite uses original `GAMESVD`, shared blink/release/sounds. Invalid + slot errors retain native validation and explanatory messages. +- [x] Mouse menu navigation follows `ReadAnyControl`: accumulated movement, + strict >60-count threshold, horizontal priority, left accept/right cancel. + Honors mouse-enabled preference; confirmation answers remain keyboard-only. + No pointer warp, absolute hit-testing or stretched coordinates introduced. +- [x] Keyboard review: save slots gain existing held-navigation repeat; shifted + US punctuation, uppercase and Caps Lock are captured when typed. Menus retain + original hotkeys and key-repeat filtering; menu Pause toggles transient music playback without changing preferences or + restarting the IMF stream (`CheckPause`/`SD_MusicOff`/`SD_MusicOn`). Gameplay + dialogs use 160-pixel message height, full menus 200, and original Message's + final-line padding rule. Non-US text input/IME remains unimplemented. +- [x] Controller audit: current engine has no SDL joystick/gamepad binding or + calibration layer. DOS gameport/Gravis rows are not advertised as functional. + Restoring usable controller input requires a separate native input feature; + no fake device detection/settings were added. +- [x] Edition audit: this port selects GOODTIMES registered WL6 layout. F1 boss + screen, six episodes and original 320×200 UI are retained. Shareware locks, + SPEAR/JAPAN/SPANISH layouts and non-GOODTIMES help need matching archive + layouts and verification; no art/chunk remapping is guessed. Native sound + volumes, display/preferences, binding editor and six portable slots remain + intentional modernizations independent of Enhanced rendering. + +Verification: all 11 Classic synthetic/owned cases passed (45.112 s); all 13 +save tests passed (41.183 s), strict C11 warnings-as-errors. New checks exercise +mouse thresholds/priority/buttons, keyboard-only confirmation, shifted text, +menu music toggle, both disk frames, quick operation failures and restart/load. +Synthetic fixtures gained invented disk chunks; no commercial assets added. + +## Batch E — verification matrix + +- [x] Full strict C11 regression suite, owned-data tests, no unexpected skips. +- [x] ASan/UBSan application and regressions. +- [x] All four original demos/5386 reference commands, Classic and Enhanced. +- [x] 320×200 UI / aspect-correct 4:3 in widescreen output. +- [x] Enhanced independence, save/config compatibility and 70 Hz/RNG checks. +- [x] Executed-DOS visual comparison: 20 exact dialog frames under DOSBox. +- [ ] Physical DOS audio/CRT comparison and exhaustive remaining UI states. +- [x] Final limitations and edition matrix, source tree/Git safety checks. + +## Remaining scope and resume point + +Portable registered GOODTIMES WL6 work in Batches A–D is implemented and +regression-tested within the limits above. The next unchecked work is physical +DOS audio/CRT comparison, followed by edition-specific layouts when matching +owned data/reference executables are available. Do not reintroduce a Game Over +card: this source's GameLoop transitions directly to CheckHighScore. + +| Area | Verified result / remaining difference | +| --- | --- | +| DOS visual oracle | Original DOS executable under DOSBox; 20 full frames, zero differing pixels. This covers quit and Loading/Saving dialogs, not every UI state. | +| DOS audio | Native original music/effect decoding, 700/140 Hz schedules, priorities, all 27 loop durations and RNG isolation covered. Exact physical DAC/OPL output and enabled-DOS menu timing remain unverified. | +| Hardware startup | Original artwork and real runtime capability lights; no fabricated DOS memory totals, EMS/XMS, ISA, gameport or Sound Source detection. | +| Input | Original keyboard/mouse behavior plus native editor repeats. No joystick/gamepad input implementation or non-US text/IME. Disabled device rows remain disabled. | +| Debug tools | Portable G/H/I/E/F/C/P/Q/W/X supported after original unlock. DOS page-cache/EMS/XMS/address viewers, VGA border registers and timing debuggers are not simulated. | +| Jukebox | All 18 songs and three banks; monotonic bank choice and title return replace DOS time/startup plumbing. Exhaustive selected/playing visual/audio comparison remains open. | +| Saves/preferences | Existing six slots, save version 1, atomic native storage, TOML settings and binding/display controls retained. No DOS ten-slot/config import. Scores have a separate versioned file. | +| Editions | GOODTIMES registered WL6 reference. Shareware/SPEAR/JAPAN/SPANISH/help layouts require matching assets and independent validation. | +| Video | Original 320×200 UI with 4:3 aspect correction; Enhanced rendering remains independent. Safe edge clipping remains; physical CRT, native Windows, ultrawide/high-DPI hardware testing is not established. | + +All commercial art/captures/reference executables remain private in temporary +or ignored build directories. WOLFSRC is unchanged; commits are confined to the +requested feature branch. That earlier validation pass did not include a push +or merge; the PR #16 follow-up below records the subsequently requested push. + +### Source-review follow-ups + +Portable debug warp and complete object counts are covered by the hidden-feature +regression. God mode now suppresses health loss while retaining the original +flash/status effects. New-game refusal/main-menu return and quick-slot reset +were corrected against CP_NewGame. The focused Classic suite passed all 11 +cases (44.956 s), audio 5 synthetic cases passed (owned case skipped in that +focused invocation), and all three synthetic/owned controls cases passed +(14.098 s). The latter now holds a mouse button across menu entry: a fresh +menu click is intentionally actionable after Batch D. + +An actual DOS executable oracle now passes **20 full 320×200 frames with zero +pixel differences**: all nine quit messages at WindowH 200 and 160, and original +Loading/Saving windows. `scripts/ui_reference.py` checks historical EXE/MAP +hashes before private instrumentation; `ui_reference.s` calls original +SetupControlPanel, Message and DrawLSAction, then exports all four VGA planes +under DOSBox. No original drawing routine is replaced. `test_dos_ui_reference.py` +compares every pixel against Revive, using only privately supplied owned WL6 +archives; its temporary commercial files/captures are removed afterwards. + +### Portable input follow-up + +MinGW's math classification macro narrowed double arguments under strict +conversion warnings. Mouse-motion validation now uses portable double limits, +with NaN/infinity regression coverage. SDL typematic events are admitted only +for editable text/navigation in names and warp input, matching the role of DOS +keyboard make repeats; gameplay, menu confirmation and held-key isolation keep +their existing event rules. All 11 focused Classic cases passed (52.051 s). +The final quit-audio source check also passed all 11 Classic cases (79.583 s). +Normal/sanitizer full suites and final portability checks are recorded below. + +### Completion timing verification + +`ID_VH.H VW_FadeIn/VW_FadeOut` use 30 tics and black; `WL_MENU.H` menu fades +use 10 tics and dark red. Completion/score transitions now retain that +original distinction. After this source correction, all 41 engine tests passed +(232.644 s), including six episode finales and final death, and all 11 Classic +cases passed (67.539 s). Final strict native/MinGW builds, Wine interaction and +the sanitized application UI/menu/level smoke checks also passed. + +## Final validation — 2026-11-03 + +| Check | Result | +| --- | --- | +| Final full normal suite | **146 passed**, no skips/failures, 550.678 s | +| Full ASan/UBSan suite | **146 passed**, no skips/findings, 1381.710 s | +| Final completion timing follow-up | 41 engine and 11 Classic cases passed; final sanitized Classic rerun: 11 passed, 77.738 s | +| Executed original DOS visual oracle | 20 frames / 1,280,000 indexed pixels identical, including both WindowH values and Loading/Saving | +| Original demo synchronization | All four recordings / 5386 commands, every traced frame, Classic and Enhanced, reference view size 15 / DOS sound off | +| Strict C11 | GCC 14.2 and MinGW GCC 14, conversion/shadow/pedantic warnings as errors; CART SDL build passed | +| Latest sanitized application | UI validation and finite menu/E1M1 smoke checks passed | +| Windows executable under Wine | UI validation, mouse/text, hidden features, high-score persistence/restart and F1–F10 save/load/end/quit paths passed | +| Native Linux X11/OpenGL | 1920×1200 output: 1600×1200 corrected canvas, 160-pixel black side borders, every 5×6 source texel equal; capture visually inspected | +| Display/render compatibility | Synthetic/owned geometry, widescreen/ultrawide, all view sizes, HUD/death effects, snapshots, saves/preferences, fixed 70 Hz and RNG isolation passed | +| Git/reference protection | WOLFSRC unchanged, no commercial assets added, feature-branch-only commits, no merge or master commits | + +The full normal pass above ran after the final completion-fade correction. +The full sanitizer run was supplemented by the final Classic rerun and latest +instrumented application smoke checks. Native C tests and application were +instrumented; the reused SDL static SDK and original DOS executable were not. +Wine/dummy-driver checks do not establish physical native-Windows behavior. + +Reproduce the normal suite after the standard CART build: + +```sh +WOLF3D_DATA=/path/to/owned/WL6 \ +WOLF3D_BINARY="$PWD/build/cart-sdl/linux/wolf3d-revive" CC='gcc -O1' \ +python3 -m unittest discover -s tests -v +``` + +Use the sanitizer build in [BUILD.md](BUILD.md#tests), then set `SANITIZE=1`, +`UBSAN_OPTIONS=halt_on_error=1` and `WOLF3D_BINARY` to that instrumented binary. +The original-DOS pixel test additionally needs DOSBox and GNU binutils; it skips +explicitly when owned data or DOSBox is absent. No skip occurred in these runs. + +Private evidence: `build/m12-final-head-full.log`, `build/m12-frozen-sanitize.log`, +`build/m12-final-head-classic-sanitize.log`, `build/m12-completion-engine.log`, +`build/m12-native.log`, `build/m12-final-app-sanitize.log`, +`build/m12-wine-final.log` and `build/m12-cart-final.log`. These remain ignored. +Physical audio/CRT comparison and the explicitly unsupported edition/hardware +features above remain open; this milestone does not claim universal DOS parity. + +## Restored entries DOS-036 and DOS-037 — PR #16 follow-up + +- [x] **DOS-036: Original Get Psyched! loading screen and progress behaviour.** + Reference: `WOLFSRC/WL_INTER.C PreloadGraphics/PreloadUpdate`, + `WOLFSRC/ID_PM.C PM_Preload`, `WOLFSRC/WL_GAME.C GameLoop` and + `WOLFSRC/ID_VL.C VL_FadeIn/VL_FadeOut`. + Implementation: `src/engine/WL_INTER.c` resumes the original drawing/waits; + `ID_PM.c/.h` exposes cache residency; `WL_PLAY.c` requests presentation after + new games, floor changes, save restoration and debug warps; `WL_MAIN.c` + consumes those requests without blocking SDL. `src/platform/sdl_video.c` + treats loading as an original DOS interface, including in Enhanced mode. + The owned `GETPSYCHEDPIC` is decoded directly from VGAGRAPH at (48,56), with + index 127 above the retained 40-pixel HUD. The progress rectangle is + (53,101), 214×2: black remainder, index 0x37 fill and 0x32 top highlight + excluding its last column. Only successfully cached, previously uncached, + non-sparse VSWAP pages advance it. Already resident pages are omitted, and + an empty preload leaves the original artwork untouched, as DOS does. + At most 32 reads run per frontend update; there is no artificial percentage + or minimum preload duration. The 30-tic black/gamepal fades and fresh-input + or 70-tic acknowledgement precede border restoration and gameplay reveal. + Death restarts do not request this screen. Simulation time, actors and RNG + do not advance during loading; no save/config format changes are involved. + Tests: `tests/loading_tests.c`, `tests/test_loading.py`; existing campaign, + save, display, menu, controls and finale SDL regressions use + `tests/finish_loading.h` to finish the new presentation before their existing + input scenarios. The dedicated test runs the actual frontend clock and SDL + event loop, independently unplanes every artwork pixel, checks exact bar + pixels/DAC palette, real page counts, 30/70/30-tic boundaries, early fresh + acknowledgement, restored bevel and freeze of RNG/simulation. Owned-data + tests cover normal progression, secret entry/return and save restoration. + 960×720, 1280×720, 1280×800 and 1720×720 windows stay unchanged, with a + centred 4:3 loading canvas and Enhanced gameplay restored afterward. + Verification: focused synthetic and owned tests passed (65.035 s, including Enhanced + smooth death rendering and intermediate fade/bar checks); an owned + loading capture was visually inspected. Full-run results are recorded below. + Limitations: native heap capacity replaces DOS main/EMS/XMS limits and disk + speed, so page totals/duration depend on actual native cache residency. + The existing level-entry reveal uses palette fading rather than adding a + separate DOS gameplay-entry fizzle. Physical CRT/DAC and native Windows, + macOS and Android display timing are not established by SDL dummy tests. + +- [x] **DOS-037: Original death-turn animation fidelity.** + Reference: `WOLFSRC/WL_GAME.C Died` (`DEATHROTATE=2`) and + `WOLFSRC/ID_VH.C FizzleFade`. + Implementation: retain the resumed `src/engine/WL_PLAY.c Died` state machine; + explicitly set the original weapon sentinel before `PLAYERDEATHSND`, match + the original float intermediate in the attacker-angle calculation, and enter + the red-fizzle phase on the tic that reaches the target. The existing + normalized shortest-arc rule already matches DOS: exactly 180 degrees chooses + the negative direction. Each elapsed 70-Hz tic turns at most two degrees, + clamped at the final angle. `WL_COMBAT.c DrawStatus` retains the last HUD + weapon icon while the held weapon is absent. `WL_PRESENT.c` normalizes the + hidden weapon to a valid snapshot index, preserving Enhanced smooth-render + validation while the authoritative DOS sentinel remains -1. The existing copied killer + position survives actor removal/reuse. Input collected during the turn/fizzle + is discarded before the original fresh-input/100-tic death acknowledgement. + The existing lives, entry-score restoration, pistol/ammo/health restart, + final-score path, red index 4 and 17-bit fizzle polynomial are preserved. + Tests: `tests/loading_tests.c` checks ten attacker/start combinations at + every Classic view size 4–19, for both synthetic and owned archives: front, + back, left, right, both 180-degree ties, single-degree wrap and oblique turns + through zero in both directions. One- and three-tic updates verify speed and + final angle; killer-position reuse, weapon sentinel, smooth Enhanced rendering + during the turn/fizzle, sound start, the first + 914 fizzle candidates, full red viewport, 100-tic wait, lives and restart + without Get Psyched are asserted. Existing combat, Classic viewport and + finale tests cover final death, rendering and subsequent lives. + Verification: the focused synthetic/owned run above passed all 320 death + scenarios. Full-run/sanitizer results follow below. + Limitations: the existing safe fizzle clips to the viewport instead of + reproducing the DOS `x>width/y>height` border overdraw. Physical audio/DAC + latency is not measured; scheduling is checked through the native engine. + +Final follow-up regression results: + +| Check | Result | +| --- | --- | +| Full normal suite | **148 passed**, no skips/failures, 596.994 s | +| Full ASan/UBSan suite | **148 passed**, no skips/findings, 1365.250 s | +| Focused loading/death | Both synthetic/owned cases passed, 65.035 s; all 320 death scenarios, intermediate fades and partial bars | +| Latest Classic follow-up | 11 passed, 53.845 s, including quicksave/load, debug warp and all viewport sizes | +| Strict C11 / SDL3 | CART application build and GCC warnings-as-errors sanitizer build passed; all 50 application units passed strict MinGW C11 compilation | +| Original demos | All four recordings passed frame/duration synchronization in Classic and Enhanced (5386 commands), as part of the normal suite | +| DOS executable pixel oracle | Existing 20 menu/disk-dialog frames remain identical; new loading pixels separately checked against the owned planar artwork and DOS bar geometry | +| SDL application | Normal and sanitized UI checks and 240-frame level/loading smoke tests passed | +| Window/aspect | 4:3, 16:9, 16:10 and ultrawide loading windows remain unchanged; loading/menus are centred 4:3, Enhanced gameplay remains wide | + +Both follow-up full runs used `CC='gcc -O1'` with owned WL6 data; the +sanitizer run used `SANITIZE=1`, `UBSAN_OPTIONS=halt_on_error=1` and the +instrumented application via `WOLF3D_BINARY`. + +Native C harnesses/application are instrumented; the reused SDL static archive +and DOS executable are not. No native macOS/Android or physical display/audio +claim is implied by dummy-driver checks. +Private evidence remains under ignored `build/m12-loading-*.log` and +`build/checks/get-psyched.*`; no commercial artwork is committed. + +### Level-entry scale transition follow-up — 2026-11-03 + +A user reported the level visibly adjusting scale on entry. The gameplay +fade-in was still classified as the DOS loading canvas by `GameLoading()`; +Enhanced gameplay appeared at 4:3 for 30 tics, then switched to its final +aspect/scaling at full brightness. A new SDL regression reproduced this in +both synthetic and owned cases before the fix. + +`WL_INTER.c GameLoadingScreen` now identifies only the DOS artwork/fade-out +phases. `sdl_video.c WorldPresentation` switches to gameplay geometry once that +fade-out reaches black, before the first visible gameplay frame. `GameLoading` +continues through gameplay fade-in, so simulation/input remain blocked for the +same duration. Loading artwork and menus retain centred 4:3 presentation; +window dimensions, configured aspect/integer scaling and game clocks are +unchanged. + +`tests/loading_tests.c` asserts the final Enhanced logical dimensions while +black, then an identical presentation rectangle throughout all 30 fade-in tics +and the first gameplay frame. It covers 960×720, 1280×720, 1280×800 and +1720×720 windows, including Auto aspect with integer-scaled DOS screens, and +checks that the actual window dimensions remain fixed. The normal focused +run passed both synthetic/owned cases (76.940 s); both also passed with +ASan/UBSan (136.583 s), without findings. All 22 display, renderer and Classic +regressions passed (186.895 s). Strict C11/SDL3 build and MinGW compilation +of the changed implementation units passed. PR #16 records this follow-up. + +### Milestone 13 follow-up + +The missing audit manifest/document are restored in +[the state-transition inventory](DOS_STATE_TRANSITIONS.md). Current fixes, +30-frame executed-DOS drawing comparisons, release validation and remaining +intentional differences are recorded in +[MILESTONE13_FINAL_FIDELITY.md](MILESTONE13_FINAL_FIDELITY.md). diff --git a/docs/MILESTONE13_FINAL_FIDELITY.md b/docs/MILESTONE13_FINAL_FIDELITY.md new file mode 100644 index 00000000..5e2f96a2 --- /dev/null +++ b/docs/MILESTONE13_FINAL_FIDELITY.md @@ -0,0 +1,285 @@ +# Milestone 13: final DOS fidelity audit and release hardening + +Branch: `feature/13-final-dos-fidelity`, based on fetched `origin/master` +`9e3c489` after PR #16. Review date: 2026-11-04. The starting working tree was clean. +`WOLFSRC/` is read-only; no commercial data, captures or executable bytes are +added. This is a conservative audit/hardening pass, not certification of complete +DOS equivalence or every future platform. + +## Confirmed defects and corrections + +1. **Missing transition inventory.** `scripts/audit_transitions.py` existed, + but both required inputs were absent. Added the authoritative + [JSON inventory](dos_state_transitions.json) and generated + [review document](DOS_STATE_TRANSITIONS.md): 106 directed transitions, + 46 phases, all 28 native UI states and all 10 original `exit_t` values. + Records link original functions, native implementation and scoped evidence, + with explicit artwork, palette, timing, sound, input and remaining findings. + Connected journeys cover startup/attract, new game, loading, pause, storage, + death/restart/final death, ordinary/secret progression, victory/articles, + qualification/name entry and quit. Caller-dependent panel return paths are + described in the rows; this is not enumeration of every input permutation. + +2. **Audit validation disappeared under Python optimization.** The previous + validator used `assert` for all checks. Replaced these with explicit failures, + added independent required-route coverage, nonempty palette/implementation/ + evidence checks, original-reference hash coverage, repository-bounded paths, + active-state mapping and nonempty connected journeys. Missing, malformed or + stale inventory/document files fail with a nonzero exit and clear diagnostic. + `--write` regenerates only after validation. Four new Python cases cover + missing/invalid/stale files, deleted required routes, source/hash/reference/ + enum/evidence corruption and `python -O`. No assets are needed for this audit. + +3. **Established quickload unnecessarily showed Get Psyched.** Original + `WL_MENU.C CP_CheckQuick(sc_F9)` invokes `CP_LoadGame(1)`, which sets + `loadedgame=true` only around `LoadTheGame`, then clears it and returns to + the existing play loop. An ordinary `CP_LoadGame(0)` retains the restart + route through `WL_GAME.C GameLoop/PreloadGraphics`. Native `Save_Load` calls + `GameRestoreClock`, which requested preloading for both cases. Clear only + that request after a successful established quickload in `UI_DISK`. + Ordinary loads, first-use slot selection, floor changes and debug warp keep + their loading presentation. No save format or simulation rule changes. + + The Classic harness previously drained any loading screen before asserting + the endpoint. Its new guard checks every frontend tic **before** that helper, + including the pending-request interval, during established quickload. The + synthetic and owned shortcut cases failed on the unfixed code, then passed + with the correction. Corruption/revalidation and ordinary loading tests stay + enabled. Focused Classic result: 11 passed, 49.010 seconds. + +## Executed original DOS presentation evidence + +The existing private runner verifies the historical EXE/MAP SHA-256 identities, +patches only its private copy, and executes original drawing routines under +DOSBox. Extended it from 20 to **30 full 320×200 indexed frames**, zero differing +pixels (1,920,000 compared indexed pixels): + +- Existing nine quit sayings at both WindowH 200 and 160: 18 frames. +- Existing original Saving and Loading windows: two frames. +- Original `LatchDrawPic(GETPSYCHEDPIC)` at (48,56): one frame. +- Original `PreloadUpdate(current,5)` for current 0 through 5: six frames, + including intermediate advancement, black remainder, 0x37 fill, 0x32 top + highlight and final-column rule. +- Original Pause latch picture at (128,64): one frame. +- Original `Message(CURGAME)` drawing at WindowH 200: one frame. +- Original `DrawHighScores` with seven historical defaults: one frame. + +The runner calls original `VW_UpdateScreen` before sampling latch drawings and +exports all four VGA planes. Native comparisons independently unplane every +pixel. Original default scores are encoded into private CONFIG records; the +user's CONFIG/saves are never copied or changed. The instrumentation remains +inside the existing bounded replacement DemoLoop region; no original drawing +routine is replaced. All generated executable/capture/data files are temporary +or ignored. There is no proprietary fixture in Git. + +These are **controlled drawing comparisons**, with the Get Psyched/Pause/new-game +art on a common menu background. They are not continuous first/subsequent/secret +loading, gameplay Pause composites, animated high-score entry, fade/palette, +death-turn/fizzle or victory/article frame comparisons. The reference config +has audio disabled. Pixel equality does not establish palette/time/audio parity. + +Existing `loading_tests.c` separately steps the actual native frontend clock, +checks partial real page reads, 30/70/30-tic waits, fresh acknowledgement, +original planar art/DAC values, ordinary/secret-entry/return/save loading, +weapon removal/death sound event, shortest arc/180° tie/speed/final angle, +intermediate red fizzle, acknowledgement and restart without Get Psyched. +Its ten attacker/start cases at all 16 Classic view sizes run against both +synthetic and owned archives: 320 death scenarios. Those are source-derived +native assertions, not newly executed-DOS death-frame evidence. + +Expanded loading geometry coverage adds exact 21:9 (1680×720) and 32:9 +(2560×720) to 960×720, 1280×720, 1280×800 and the previous 1720×720 case. +Each checks the final Enhanced geometry while black, the same presentation +rectangle through every reveal tic and the first gameplay frame, and unchanged +window dimensions. Alternating integer/fit settings exercise the DOS canvas +independently from Enhanced gameplay. An initial expanded test run omitted the +new expected logical heights; the test matrix now keeps width/height/expected +height together. No renderer change was necessary. + +## Gameplay, audio and release review + +| Area | Original / native review and regression evidence | Result and boundary | +| --- | --- | --- | +| Movement/turning | `WL_AGENT.C ControlMovement` / native controls and movement; four original demo state traces | Fixed-point/70 Hz and four-tic demo rules retained; no demonstrated new mismatch in sound-off reference scope. | +| Weapons/ammo | `WL_AGENT.C T_Attack`, `attackinfo`, inventory functions / `WL_COMBAT.c`; combat/demo tests | Firing, switching, clip limits, pickup quantities and attack clocks retained. | +| BJ face/damage | `WL_AGENT.C UpdateFace/TakeDamage`, `WL_PLAY.C` palette shifts / native combat/palette tests | Health/face/flash rules covered; enabled-DOS gatling-sound RNG exception remains below. | +| Enemies/bosses | `WL_STATE.C`, `WL_ACT2.C` / native actor/state/projectile/victory code; demo and six controlled finales | Alert/attack/pain/death, projectile and logical digitized death-delay assertions retained. Not six complete human playthroughs. | +| Doors/pushwalls | `WL_ACT1.C` / native door/grid/pushwall code; demo/campaign/save tests | Original timing, occupancy, secret counting and continuation retained. | +| Awards/exits | `WL_AGENT.C GivePoints/GiveExtraMan/GetBonus`, `WL_GAME.C ElevatorBackTo/GameLoop` / combat/campaign | 40000-point extra-life thresholds, nine-life cap, awards, ordinary and secret routing retained. | +| Music/effects | `ID_SD.C` schedules and original song/digitized maps / `ID_SD.c`, `sdl_audio.c`; audio tests | IMF 700 Hz/effect 140 Hz and PCM rate, priorities, track transitions, volumes, pause, disabled output and RNG isolation covered. | +| FM/PCM balance | Existing ×4 FM gain in the wide accumulator before saturation; PCM path unchanged | No measured physical-device evidence warrants changing it. Software loop/headroom tests are not a physical loudness calibration. | +| Asset safety | `ID_CA.c`, `ID_MAP.c`, `ID_PM.c`, `ID_SD.c`; malformed/truncated/archive bounds tests | Bounded expansion, offsets, sprite posts, map dimensions and allocation failure paths retained. No new decoding defect demonstrated. | +| Storage | Native save/config/high-score staging and `save_file.c` atomic writes; corruption/failed-write/restart tests | Validate before applying state; preserve protected/unsupported files and failed replacement. No DOS format compatibility added. | +| Lifecycle | `main.c`, SDL audio/video/input; repeated game/load/floor/finale and memory counters | Owned resources released on stop/shutdown; audio failure can continue silently. Focus/capture/fullscreen recovery covered by SDL regressions. | +| Rendering | Classic framebuffer, viewport/HUD tests; Enhanced snapshot/render/display tests | 320×200 UI with corrected 4:3 canvas, all view sizes 4–19; widescreen gameplay shares original rules, interpolation stays optional. | + +No synthesizer, renderer, simulation, file-format or dependency replacement was +needed. Strict C11 and SDL3/software rendering remain intact. Native Windows, +macOS, WebAssembly and Android viability is preserved at the source/architecture +level; only available Linux and MinGW/Wine builds are tested here. No Android +controls were added. + +## Actual commands and results + +Final runs use owned registered WL6 data, GCC with `CC='gcc -O1'`, the existing +static SDL3 SDK and temporary fixture/storage directories. Logs are ignored +under `build/m13/`. The original DOS executable and reused SDL archive are not +sanitizer-instrumented. + +```sh +./build/tools/cart build --profile cart-sdl +python3 scripts/audit_transitions.py --write +python3 scripts/audit_transitions.py --check +python3 -O scripts/audit_transitions.py --check +WOLF3D_DATA=/path/to/owned/WL6 \ +WOLF3D_BINARY="$PWD/build/cart-sdl/linux/wolf3d-revive" CC='gcc -O1' \ +python3 -m unittest discover -s tests -v + +gcc -std=c11 -O1 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -fsanitize=address,undefined -fno-omit-frame-pointer -g \ + -Isrc -I../cart/vendor/SDL/include \ + src/main.c src/engine/*.c src/platform/*.c \ + ../cart/vendor/SDL/build/libSDL3.a -pthread -lm \ + -o build/m13/wolf3d-revive-sanitize +SANITIZE=1 UBSAN_OPTIONS=halt_on_error=1 CC='gcc -O1' \ +WOLF3D_DATA=/path/to/owned/WL6 \ +WOLF3D_BINARY="$PWD/build/m13/wolf3d-revive-sanitize" \ +python3 -m unittest discover -s tests -v +``` + +| Check | Current result / private log | +| --- | --- | +| CART SDL3 build | Passed; `cart-final.log` | +| Full normal suite | **152 passed**, no skips/failures, **592.691 s**; `full-normal.log` | +| Full ASan/UBSan suite | **152 passed**, no skips/findings, **1131.372 s**; `full-sanitize.log` | +| Audit validation | 106 transitions / 46 phases / 28 UI states / 10 DOS exits; normal, direct executable and `python -O` checks pass | +| Focused quickload regression | Failed before fix in both synthetic/owned shortcut cases; all 11 Classic cases passed after fix, 49.010 s | +| Expanded focused loading/death | Both synthetic/owned cases passed, 96.663 s; `loading-final.log` | +| Executed original DOS UI | 30 complete indexed frames identical; also included in full normal/sanitizer suites | +| Fresh executed original demos | All 5386 commands matched current native state trace; `dos-demo.log` | +| Strict native / MinGW C11 | GCC 14.2 sanitized application; all 50 units compiled and Windows executable linked with MinGW GCC 14; `mingw.log` | +| Application smoke / native Linux | Normal and sanitized checks/menu/level/audio-disabled cases pass; X11/software captures inspected; `smoke.log`, `native-x11.log` | +| Windows under Wine | Four UI/level/menu/loading smoke commands passed; `wine.log` | +| CART regressions | SDL3 and desktop-output-directory scripts passed; `cart-sdl3.log`, `cart-desktop.log` | +| Source/data protection | No `WOLFSRC/` change; no commercial assets or executables staged; published commit trees checked against local trees | + +The fresh DOS reference comparison used: + +```sh +python3 scripts/demo_reference.py --data "$WOLF3D_DATA" \ + --output build/m13/dos-demo-reference --fast +SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy dosbox \ + -c 'config -set cpu cycles=100000' \ + -c 'mount c build/m13/dos-demo-reference' -c c: \ + -c 'trace.exe nowait' -c exit +gcc -std=c11 -O1 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -Isrc -I../cart/vendor/SDL/include tests/demo_trace.c \ + src/engine/*.c src/platform/*.c ../cart/vendor/SDL/build/libSDL3.a \ + -pthread -lm -o build/m13/demo-trace +build/m13/demo-trace "$WOLF3D_DATA" > build/m13/native-demo.csv +python3 scripts/compare_demo_traces.py \ + --dos build/m13/dos-demo-reference/TRACE.BIN \ + --native build/m13/native-demo.csv +``` + +MinGW compiled every `src/**/*.c` independently with +`x86_64-w64-mingw32-gcc -std=c11 -O1 -Wall -Wextra -Wpedantic -Wconversion +-Wshadow -Werror`, `-Isrc` and the existing SDL3 3.4.18 MinGW SDK include path, +then linked all 50 objects with that SDK's `-lSDL3 -lm`. +The resulting Windows executable passed `--check-ui`, `--check-level`, +`--menu --frames 10` and `--level --frames 240` under Wine/dummy drivers. +The reused private Wine prefix reported an unsupported pre-existing config; +it preserved that file and continued successfully with defaults. + +Normal and sanitized Linux executables passed `--check-assets`, `--check-ui`, +`--check-level`, `--menu --frames 30`, `--level --frames 240` and the same level +smoke with `--no-audio`, using dummy software video/audio and isolated +`XDG_DATA_HOME`. Native Linux X11/software finite menu/level runs also passed +with isolated preferences; the private 960×720 Get Psyched readback was visually +inspected. This does not replace physical fullscreen/device/input testing. +CART's `tests/test_sdl3.sh` and `tests/test_desktop_dirs.sh` passed in the sibling +CART checkout using this repository's absolute `build/tools/cart` path. + +All four original recordings are checked against the existing independent DOS +reference hashes in both Classic and Enhanced: 691/1899/1140/1656 commands, +2764/7596/4560/6624 tics, total 5386 commands. This pass replays the recordings +against those references. A fresh private `demo_reference.py --fast` DOSBox +execution also matched the current native trace for all 5386 commands and the +expected four durations (`build/m13/dos-demo.log`). Fast instrumentation skips +wall-clock waits while preserving original four-tic simulation and sound-off +settings; this is not enabled-sound or physical-time evidence. + +The first exploratory full run overlapped test/oracle edits and is not final +validation (its 20/29-frame expectation differed during the runner extension). +Only completed final runs are reported above. No failing assertion was removed +or weakened. The quickload failure-before/fix-after and expanded geometry test +correction are preserved in private logs. + +## Remaining differences and unverified claims + +The inventory tracks eight finding groups and concrete closure criteria. +The following prevent a blanket DOS-equivalence or hardware-release claim: + +- Gameplay entry uses a native palette fade and death restart redraws + immediately, instead of the DOS `fizzlein` reveal. Red death fizzle deliberately clips to the viewport instead + of DOS's inclusive edge overdraw. These known presentation differences remain. +- Native heap cache capacity and reads per update replace DOS main/EMS/XMS/disk + cadence. Disk activity artwork follows native work phases rather than DOS + serialization chunks. No claim of identical preload totals/duration. +- Continuous DOS death, fades, victory/ending and animated high-score entry + remain independently unverified. The controlled drawings above do not close + those findings, and there is no physical VGA/CRT/DAC comparison. +- Physical OPL/Sound Blaster balance and latency are uncalibrated. Original DOS + `UpdateFace` skips RNG while `GETGATLINGSND` plays; native gameplay intentionally + remains independent of enabled audio. Silent demo parity does not cover that + enabled-sound branch. DOS death also waits for active FM/PC sound completion + after acknowledgement; native has no separate completion gate. Its early-ack + timing relative to FM completion is unverified. Native HUD normalizes global + demo floor numbering. +- Six atomic native saves, separate versioned scores/TOML settings, native + controls/display/volume panels and separate UI entropy remain intentional. + There is no DOS ten-slot save/config import or byte-compatible storage. +- Registered GOODTIMES WL6 is the supported reference. Shareware locks, + SPEAR/JAPAN/SPANISH layouts and non-GOODTIMES help need matching owned data + and separate source/artwork verification. BIOS text mode, ISA, EMS/XMS, + Sound Source/gameport diagnostics and DOS hardware debuggers are not emulated. + Native joystick/gamepad calibration/binding and non-US text/IME are absent. +- SDL dummy fullscreen/integer/fit/focus checks and Wine are not physical + native-Windows, ultrawide/high-DPI/multimonitor or live audio-device testing. + macOS, WebAssembly and Android builds/devices were not available for execution. + +Shell Git/gh had no authentication credentials. Publication uses the connected +GitHub app, preserving the small commit messages and checking each remote tree +SHA against the corresponding local tree. The original local commits are kept +on an archive branch when reconciling the app-created commit metadata. + +The changes are ready for review with these limits. A stable engine regression +result must not be described as historical equivalence beyond its evidence. + +## DOS mouse preference follow-up — 2026-11-04 + +The user explicitly selected **Keep DOS-style stepping**. The preceding +pointer-following implementation was reverted. Current menus retain original +strict >60-count movement, horizontal priority and mouse-button actions. +Menus now use SDL relative capture while focused and mouse input is enabled: +the desktop pointer is hidden, the DOS gun cursor is the sole row indicator, +and movement cannot run into the edge of the desktop. Menu capture is separate +from gameplay capture, so menu movement/buttons never feed player actions. +Focus loss, pending display changes, disabling the mouse and shutdown release +the native capture; focus regain restores it for the current menu. Accumulated +motion is cleared at capture boundaries. + +The original threshold/priority assertions remain, supplemented by checks for +native relative mode, release/regain on focus and enable changes, and 100 idle +tics without selection drift. Both synthetic and owned interface cases run. + +Validation: CART build passed; **12 Classic cases passed** (45.112 s), +including synthetic/owned DOS mouse checks; **12 ASan/UBSan Classic cases +passed** (67.716 s, no findings); **24 controls/display/menu/save regressions +passed** (84.359 s). All 50 application units passed strict MinGW C11 compilation +and linked. Four inventory regressions passed. Private logs are +`dos-mouse-classic-final.log`, `dos-mouse-classic-sanitize.log`, +`dos-mouse-regressions.log`, `dos-mouse-mingw.log` and `dos-mouse-audit.log`. + +These focused checks supplement the preceding full 152-case validation; the +full runs predate this menu-capture follow-up. WOLFSRC remains unchanged. diff --git a/docs/MILESTONE2.md b/docs/MILESTONE2.md new file mode 100644 index 00000000..a1cfa823 --- /dev/null +++ b/docs/MILESTONE2.md @@ -0,0 +1,109 @@ +# Milestone 2: original WL6 title graphics + +The original title screen now displays from the user's Steam files in an SDL3 +window. This is the title-only dependency slice of the original engine, not a +replacement engine or a complete gameplay port. No Wolf4SDL/wolf3d-lib code +was imported. `WOLFSRC/` is unchanged. + +## Original path and ported modules + +`WOLFSRC/WL_MAIN.C:DemoLoop` calls `CA_CacheScreen(TITLEPIC)` then updates the +display. The new entry point follows that path after starting memory/cache +services and selecting the original palette. The original title index is 87. + +| New file | Original owner and changes | +| --- | --- | +| `src/engine/ID_MM.c`, `.h` | `WOLFSRC/ID_MM.C/H`: heap-backed stable owner handles replace paragraphs and far pointers. `MM_GetPtr`, `MM_FreePtr`, `MM_SetPurge`, `MM_SetLock`, `MM_SortMem`, startup/shutdown retain ownership and purge/lock roles. Allocations are zero-initialized, bounded by a 64 MiB payload budget, and checked. Purging nulls the registered owner; no relocation is necessary. | +| `src/engine/ID_CA.c`, `.h` | `WOLFSRC/ID_CA.C/H`: portable file access, explicit little-endian dictionary/24-bit offsets/chunk sizes, bounded `CAL_HuffExpand`, `CAL_SetupGrFile`, `CA_CacheGrChunk`, `CA_CacheScreen` and picture table. Huffman root 254, child indices 256..510 and LSB-first consumption match the original assembly; the DOS pointer-optimization step is unnecessary. | +| `src/engine/ID_VL.c`, `.h` | `WOLFSRC/ID_VL.C/H`: `VL_MemToScreen` translates four consecutive VGA planes into 320×200 indexed pixels. `VL_SetPalette` retains 0..63 DAC values. RGBA conversion expands six-bit channels by bit replication and supplies opaque alpha. | +| `src/engine/GFXV_WL6.h` | Original generated resource indices and constants copied from `WOLFSRC/GFXV_WL6.H`, with any DOS EOF marker removed. | +| `src/engine/gamepal.inc` | All 256 original colors from the tracked `GAMEPAL.OBJ` segment-1, offset-0 LEDATA payload (768 bytes). No Steam graphics embedded. | +| `src/platform/sdl_video.c`, `.h` | SDL-only window/renderer/streaming texture, indexed-to-RGBA upload, nearest sampling and centered 4:3 logical presentation. A 320×200 texture fills a 320×240 logical viewport. Resize, redraw, palette updates, Escape and close events are supported. | + +Portable functions return success/failure and carry explicit buffer sizes where +the DOS versions assumed valid memory. Errors propagate to the entry point; +partially loaded chunks are freed and startup failures close the archive. +Owner handles must stay at a stable address until freed, matching the original +memory manager's registered-pointer contract. Shut down CA before MM. + +Cache hits reuse the decoded buffer and clear its purge level, as in the +original. Title decode now goes through that cache and then `VL_MemToScreen`, +rather than writing Huffman output directly to hardware VGA planes. This keeps +the original decoded byte order while separating hardware presentation. +The graphics picture table and title remain resident until shutdown or purge. +This slice does not implement cache levels or EMS/XMS page management. + +## Data and validation boundaries + +`--data` accepts an explicit directory, including paths with spaces. The loader +recognizes Steam's uppercase names and all-lowercase copies. It never changes +the current directory, copies an archive or writes configuration/saves there. + +The supported graphics profile is the checked-in 149-chunk WL6 layout: +450-byte VGAHEAD, 255-node dictionary (1020 bytes, or 1024 with the unused final +entry), 132 picture dimensions and a 320×200 title. Missing/malformed graphics, +invalid dictionary references/cycles, sparse/missing title data, nonmonotonic +or out-of-file offsets, truncated input and oversized expansions fail with a +diagnostic and exit status 1. Input files are limited to 32 MiB and individual +compressed/expanded chunks to 4 MiB. The terminal header offset must match the +archive size. Files are read on demand rather than loading the entire archive. + +The full expected WL6 file set is checked for presence, nonempty size and +readability: VSWAP, VGAHEAD/VGADICT/VGAGRAPH, MAPHEAD/GAMEMAPS and +AUDIOHED/AUDIOT. Only graphics formats are parsed in this milestone. Presence +of maps/audio does not establish their semantic validity or full edition +compatibility. Arbitrary case mixtures and different WL6 resource layouts are +not supported yet; unsupported layouts fail explicitly instead of guessing. + +## Other changed files + +- `src/main.c`: replaces the milestone-1 probe with title startup/lifecycle; + `--data`, `--check-assets`, finite `--frames`, optional private `--capture`. +- `cart.toml`: keeps existing targets/SDL profiles and removes the probe-only + define; recursive CART discovery builds all five active C files. +- `src/w3r_types.h`: baseline comment updated; fixed-width definitions retained. +- `.gitignore`: additionally ignores BMP/PPM captures of game artwork. +- `tests/engine_tests.c`, `tests/video_tests.c`, `tests/test_engine.py`: + synthetic fixtures, C units, loader/CLI failures, SDL readback and optional + owned-data comparison. Existing Git-protection tests are unchanged. +- README and BUILD/PORTING/LICENSING guides now describe the implemented title + path, limits, provenance and reproduction commands. + +CART required no new changes. Its pre-existing milestone-1 filesystem fix, +test and testing-document modifications were preserved without alteration. +No compiler install, dependency download, commit or push was performed. +Origin and upstream protections remain configured, including the existing +invalid `upstream` push URL `DISABLED` and `.githooks` pre-push guard. + +## Verification results + +- GCC/C11 CART build with all configured strict warnings: passed without new + warnings; repeat builds report up to date. +- Actual Steam WL6 title: loaded in place, displayed in an SDL3 window, and a + local render capture visually inspected at 960×720. Captures stay in ignored + build output. No commercial data or rendered artwork was added to Git. +- Sixteen unittest cases passed with `WOLF3D_DATA` enabled, also passing with + ASan/UBSan for the application and C test binaries. Includes bounded Huffman + malformed-stream corpus, ownership/purge/lock/shutdown, invalid files/offsets, + dimensions, expansion limits, cache hits and repeated startup/shutdown. +- Independent Python decoder matched every indexed title byte and every RGBA + byte from the C path against the real Steam archive. Palette expectations + came independently from the original tracked OMF resource. Synthetic + archive round trips compare all pixels as well. +- SDL dummy/software readback verified nearest color boundaries, palette-only + updates, Escape handling, wide 1000×600 and tall 600×1000 resize viewports + (800×600 at x=100, and 600×450 at y=275 respectively). +- MinGW C11 compile-only checks with warnings as errors passed for all five + active C files. Windows linking/runtime remain untested. +- Existing CART SDL3 regressions (including raylib/Android fixtures) and its + output-directory regression passed. No CART source changes were necessary. +- Git whitespace checks and unchanged `WOLFSRC/` checks passed. + +## Remaining work + +The static title remains until Escape/close. Original fades, the 15-second +attract sequence, menus, fonts, PCM/OPL, simulation timing and gameplay are not +implemented. There is no fullscreen toggle or SDL_GPU path. Next extend +original VL/VH/CA drawing to menus and fonts, followed by bounded map/VSWAP +loading and deterministic fixed-point/RNG helpers for the gameplay port. +Game movement, doors, enemies and audio stay out of this graphics milestone. diff --git a/docs/MILESTONE3.md b/docs/MILESTONE3.md new file mode 100644 index 00000000..00437d2d --- /dev/null +++ b/docs/MILESTONE3.md @@ -0,0 +1,130 @@ +# Milestone 3: original menus, input and attract screens + +The application now runs the original WL6 title -> credits -> high-score +sequence, then opens the main menu. Any supported key during attract mode +opens the menu early. Original fonts, graphics, colors, layout, text alignment, +gun selection indicator and palette interpolation come from `WOLFSRC/`. +No modern UI toolkit, replacement engine or reference-port code is used. + +## Run and controls + +From the repository root: + +```sh +./build/tools/cart build --profile cart-sdl +./build/tools/cart run --profile cart-sdl -- \ + --data "$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" +``` + +Add `--menu` to start directly in the control panel. Up/Down navigate, wrapping +and skipping unavailable rows. Enter/Space selects. V, B and Q select View +Scores, Back to Demo and Quit, respectively. Escape in the main menu opens +quit confirmation: Y exits, N/Escape cancels. Any key on View Scores returns +to the menu. Closing the SDL window exits directly. + +New Game, Sound, Control, Load Game, Save Game and Change View are disabled, +drawn in the original `DEACTIVE` color and skipped by navigation/shortcuts. +The first enabled selection is View Scores. No action pretends to start a game, +load/save data or configure unported audio/input. The original mouse legend +is retained as artwork; mouse navigation is not implemented in this slice. + +The selected GOODTIMES layout in the original VERSION.H has nine actual rows, +without Read This. Its row count is bounded by the actual array, avoiding the +historical release's hardcoded ten-row/conditional-array mismatch. + +## Ported modules and provenance + +| File | Source and behavior | +| --- | --- | +| `src/engine/ID_VH.c/.h` | `ID_VH.C/H`: buffered planar picture blits, original eight-pixel VWB picture alignment, bars/lines and transparent proportional fonts. Font headers and every glyph offset/extent are decoded explicitly and checked before drawing. Low-level `VL_MemToScreen` continues to support arbitrary pixel coordinates. | +| `src/engine/ID_US_1.c/.h` | `ID_US_1.C`: `US_Print`, newline/window positioning, proportional measurement. String literals are no longer modified in place. | +| `src/engine/WL_MENU.c/.h` | `WL_MENU.C/H`: `ClearMScreen`, `DrawStripes`, beveled `DrawWindow`, `DrawMainMenu`, `SetupControlPanel`, tic-driven `HandleMenu` and original quit `Message` geometry. Coordinates, text, palette indices and gun pictures retain original ownership. | +| `src/engine/WL_INTER.c` | `WL_INTER.C:DrawHighScores`, default seven-entry table from `ID_US_1.C`, original picture headings, episode/level labels and fixed-width digit glyphs 129 onward. These are the authored defaults, not invented player scores. | +| `src/engine/ID_IN.c/.h` | `ID_IN.C/H`: original set-1 key namespace, make/break state, LastScan/LastASCII and clear operations. Press edges survive a quick down/up between frames, while OS auto-repeat is ignored. | +| `src/engine/WL_MAIN.c/.h` | `WL_MAIN.C:DemoLoop` plus control-panel flow, converted from blocking loops to explicit states/deadlines. Main-menu scores, return-to-attract and original Y/N quit behavior are wired to real implemented actions. | +| `src/engine/ID_TIME.h` | Original `TickBase=70` semantics expressed as an overflow-safe nanoseconds-to-tics conversion, independent of presentation count. | +| `src/engine/ID_VL.c/.h` | Incremental `VL_FadeIn`, `VL_FadeOut`, `VL_FadeStep`: original six-bit `orig + delta*i/steps` interpolation, including C integer truncation toward zero and exact final palette. | +| `src/platform/sdl_input.c/.h` | SDL physical scancodes map to set-1 codes. Both edges are forwarded; modifier/keypad aliases remain held until all matching physical keys release. Focus loss clears physical and logical key state. | +| `src/platform/data_file.c/.h` | Portable directory enumeration for ASCII case-insensitive WL6 matching on Linux/Windows. Exact spelling wins; otherwise ambiguous duplicate spellings fail instead of selecting an arbitrary file. | +| `src/platform/sdl_video.c/.h` | Monotonic SDL clock, sleeping, key/focus/quit event forwarding, safe partial-init cleanup, repeated startup/shutdown and cached framebuffer/palette texture uploads. | +| `src/main.c` | Startup/lifecycle and CLI, now without SDL-specific headers or calls. `--check-ui` validates/draws the complete UI slice without opening a window; `--check-assets` retains the title-only check. | + +`ID_CA.c/.h` now delegates filename resolution to the platform file helper and +shares graphics error reporting with font/picture validation. Existing Huffman, +offset, decompression and allocation bounds remain in force. `cart.toml` keeps +the same C11/SDL_Renderer configuration; its scope comment is updated. CART +itself required no changes. The prior CART working-tree changes were preserved. + +## Timing and transitions + +The original hold times are 15 seconds for TITLEPIC, 10 for CREDITSPIC and 10 +for DrawHighScores. The 30-tic attract fades and 10-tic menu fades have their +own deadlines; hold time starts after fade-in, as in the original blocking +sequence. Black attract fades and dark-red menu fades use the original target +colors. Completed transitions catch up to scheduled times after a delayed +frame rather than resetting the clock to the latest presentation. + +Original demo playback is not implemented or simulated. At the demo handoff, +the program fades into the menu. Back to Demo restarts the supported sequence. +This is an explicit milestone boundary; the title/credits/scores order and +hold durations are preserved. The menu gun blinks with the original >8/>70-tic +thresholds; held arrows repeat on a 20-tic deadline. Shortcuts and navigation +skip disabled rows. The original blocking half-step gun-slide animation is +not ported; selection moves directly between rows. Audio feedback is also +absent until audio dependencies are ported. + +Quit confirmation uses the first original English quit phrase; random phrase +selection awaits the original RNG. N/Escape cancels without resetting the +selection, and Y runs the original dark-red menu fade before closing. Saved +configuration/high-score import, high-score entry, help, gameplay-related +submenus, PG-13/signon startup screens, audio and demo playback remain outside +this milestone. No gameplay simulation or frame-rate-dependent movement was +introduced. Windows linking/runtime, fullscreen and gamepad remain future work. + +## Resource and initialization hardening + +The SDL initializer owns cleanup at every failure stage and preserves the +failure message across teardown. Startup can be retried after a failed renderer +creation, and shutdown is idempotent. SDL-specific code stays under platform/. +The frame loop sleeps between event polls; it does not wait on tics in a spin +loop. Tests inject virtual ticks directly into the original UI flow. + +Unchanged pixels and palette reuse the existing texture contents. Palette-only +changes still recolor the complete indexed image. Exact snapshots are compared +so direct framebuffer writes by original-style engine code remain supported; +resizing never requires re-decoding assets or a fresh texture upload. Renderer +presentation remains separate from the 70 Hz UI/timing updates. + +## Validation + +Commands are in [BUILD.md](BUILD.md). Results: + +- CART GCC/C11 build with strict warnings passed; no new warnings. Repeat build + reports up to date. +- Twenty unittest cases passed with the owned Steam path enabled, including all + prior Git-protection, memory, Huffman, framebuffer and malformed-archive tests. +- The same suite passed with ASan/UBSan instrumentation of the application and + C tests, including clean UI teardown, repeated SDL lifecycles and renderer-init + failure cleanup. The pre-existing SDL static archive is not instrumented. +- Synthetic font/picture archives test transparency, metrics, immutable multiline + text, malformed heights/offsets/truncation, menu drawing, selection wrapping, + disabled actions, shortcuts, held repeats, fades and exact/coarse attract clocks. +- SDL dummy/software tests inject key-down/up and repeat/focus events. A complete + SDL-event-to-menu test opens the menu from the title, navigates held arrows, + views scores, cancels quit and confirms a clean exit. Texture-upload counts + verify unchanged frames/resizes do not re-upload; palette changes do. +- Steam title pixel/palette oracle comparison remains passing. Real menu/fonts, + credits and high-score screens loaded in place and were visually inspected + via SDL readbacks. Captures remain under ignored build output. +- All active C sources passed MinGW C11 compile-only checks with warnings as + errors. Native Windows execution is not claimed. +- Existing CART SDL3 suite (including raylib/Android fixtures), desktop output + directory, Android profile/icon and Linux macro regressions passed. Expected + existing icon-copy warnings remain unchanged. +- Whitespace, Git safeguards, original-source preservation and asset-ignore + checks passed. No game assets, binaries, captures or generated fixtures were + added to Git. No commits or pushes were performed. + +Milestone 4 can now add bounded GAMEMAPS/MAPHEAD and VSWAP loading, deterministic +fixed-point/RNG helpers, original ray traversal and first-level movement behind +this working original UI. No Ironclaw 3D work was started. diff --git a/docs/MILESTONE4.md b/docs/MILESTONE4.md new file mode 100644 index 00000000..881f2896 --- /dev/null +++ b/docs/MILESTONE4.md @@ -0,0 +1,170 @@ +# Milestone 4: E1M1 walls and movement + +New Game now genuinely loads Episode 1, Level 1 from the user's WL6 archives, +renders its original walls and doors, and allows walking, turning, running, +strafing and normal-door operation. Escape ends the walk session and returns +to the original menu. This is a verified wall-and-movement slice, not a complete +combat-capable Wolfenstein game or a completed campaign playthrough. + +## Build and run + +From the repository root: + +```sh +./build/tools/cart build --profile cart-sdl +./build/tools/cart run --profile cart-sdl -- \ + --data "$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" +``` + +Press a key to open the menu, then choose New Game. It is enabled only after +map, texture, spawn, status-art and initial ray-render validation succeeds. +There are no invented episode/difficulty selection screens: the action starts +E1M1 directly. Other episodes and difficulty behavior are not exposed. + +| Key | Action in the level | +| --- | --- | +| Up / Down | Forward / backward | +| Left / Right | Turn | +| Alt + Left / Right | Strafe | +| Shift | Original run speed | +| Space | Operate an adjacent normal door | +| Escape | End this walk session and return to the menu | + +Space operates the door in the cardinal direction the player faces. Approach +within one tile before using it. Key-locked doors stay locked; inventory is not +implemented. The elevator switch, secret pushwalls and level completion are +not activated. Escape is not a pause/save/resume feature; New Game restarts +E1M1. Existing menu controls, attract screens, scores and quit confirmation +continue working. + +Diagnostics (same required `--data` argument): + +```sh +./build/cart-sdl/linux/wolf3d-revive --data /absolute/path/to/WL6 --check-level +./build/cart-sdl/linux/wolf3d-revive --data /absolute/path/to/WL6 --level +``` + +`--check-level` validates and renders the initial world without SDL window +creation. `--level` starts that world directly. `--menu`, `--check-assets`, +`--check-ui`, `--frames N`, `--capture PATH.bmp` and `--help` remain available. +The optional initial capture is at full palette brightness before fade-in. +Keep captures private and in ignored build output. + +## Source port, in dependency order + +| Phase / files | Original implementation and changes | +| --- | --- | +| Input fixes: `ID_IN.c/.h`, `WL_MENU.c/.h` | Shortcut presses are queued and consumed once, in order, instead of repeatedly reading stale LastASCII. Escape, Enter and Space edges are consumed together with Escape taking priority. Existing SDL physical aliases, key-up and focus-loss clearing remain intact. Quick movement taps persist until a simulation tic, even if both make/break arrive between presentations. | +| A: `ID_FILE.c/.h`, `ID_MAP.c/.h`, `ID_CA.c` | Original `ID_CA.C:CAL_CarmackExpand`, `CA_RLEWexpand`, `CA_CacheMap`; explicit little-endian MAPHEAD offsets, 38-byte map headers and all three 64×64 word planes. Carmack near/far references preserve overlapping forward copies and escaped tag bytes. Both expansion layers have source/output bounds. Raw disk planes remain available unchanged. | +| B: `ID_PM.c/.h` | Original `PML_OpenPageFile` and `PM_GetPage`: VSWAP count/sprite/sound boundaries, 32-bit page offsets and 16-bit lengths. Pages load on demand into stable MM-owned caches. Walls retain their original 64-column × 64-row, column-major byte order. Sprite post streams decode with a separate opacity mask and signed pixel-pool bias; sprite rendering is not yet connected. | +| C: `WL_DEF.h`, `WL_ASM.c`, `WL_DRAW.c`, `WL_SCALE.c` | Original `WL_MAIN.C:BuildTables/CalcProjection/SetupWalls`, `WL_DR_A.ASM:AsmRefresh`, `WL_DRAW.C:FixedByFrac/CalcHeight/Hit*Wall/Hit*Door/ScalePost`, `WL_SCALE.C:BuildCompScale`. The quadrant-specific x/y stepping, vertical/horizontal entry tests, door midpoint tests, texture orientation, distance projection and wide-post height reuse are retained. Portable C emits original source-pixel scaling runs instead of executable x86 bytes. | +| D: `WL_GAME.c`, `WL_AGENT.c`, `WL_PLAY.c`, `WL_ACT1.c` | Original `SetupGameLevel`, info-plane player spawn, door/jamb marking, `PollKeyboardMove`, `ControlMovement`, `Thrust`, `TryMove`, `ClipMove` and door open/close state. Runtime tilemap remains x-major. Player coordinates remain 16.16; turning preserves anglefrac and the original square collision radius/axis-slide order. | +| E: `WL_MAIN.c/.h`, `WL_MENU.c/.h`, `main.c` | Readiness-gated New Game, game-state startup/teardown, input routing, world fades, Escape-to-menu and direct/headless level diagnostics. Missing or malformed level resources disable New Game while preserving the working title/menu UI. | + +All work is under `src/`; `WOLFSRC/` remains unchanged. The C translation is +from the original local source and assembly, not a tutorial DDA, Wolf4SDL or +wolf3d-lib substitution. No third-party implementation was imported. Original +module/function ownership and derivation are identified in comments. + +## Preserved calculations and explicit boundaries + +- `FixedByFrac` takes a two's-complement coordinate and a **signed-magnitude + fraction**, using the low 16 bits of the second operand and its high sign + bit. It is not generic signed 16.16 multiplication. Unsigned/wide arithmetic + makes wrap/truncation explicit without signed-overflow UB. Cardinal table + values follow the original float-store table construction. +- Ray traversal follows the original two linked grid walks and quadrant cases, + including tie ordering and 16-bit fractional partial steps. Closed/moving + doors intersect at tile centers; opening position changes both leading-edge + visibility and texture coordinates. Door jamb pages use `PMSpriteStart-8`. +- The framebuffer remains 320×200 indexed VGA data. The source's default + size-15 view is 240×120 at (40,20), above the original status-bar artwork and + beveled play border. Wall height is still in quarter-pixel units; the scaler + directory's two-pixel, minimum-size and large-index quantization, centering and + clipping are reproduced. Ceiling/floor use original E1M1 palette indices. +- Keyboard controls use BASEMOVE=35 / RUNMOVE=70, MOVESCALE=150, + BACKMOVESCALE=100, ANGLESCALE=20 and MINDIST=0x5800. No invented acceleration, + diagonal normalization, floating-point player coordinates or FPS scaling was + introduced. +- Each elapsed 70 Hz tic runs the original **one-tic** movement path; rendering + is independent. This makes identical held-input intervals deterministic at + different presentation schedules. At most MAXTICS=10 run per update; excess + long-pause time is discarded. Variable-size DOS frame batching can round + movement differently; this implementation does not claim bit-identical + traces for every original host frame rate. +- Normal doors move by 1024 position units per tic, become traversable when + fully open, and try to close after the original OPENTICS=300. Player overlap + prevents closure. Locked-door rejection is retained with no keys granted. + Area connectivity, actor obstruction and positional audio hooks await their + original dependencies. + +## Validation and ownership + +Map loading checks map index, table/header size, dimensions, plane offsets, +overlap and file bounds, both expanded-length fields, and compressed references. +The world requires a solid perimeter, one collision-free player start, valid +wall/area codes, bounded door counts and valid door jambs. A failed map decode +does not replace an already cached map. + +VSWAP validates directory bounds/order, sparse entries, page overlap, sprite/ +sound boundaries and exact 4096-byte wall pages. Sprite decoding checks column +ranges, command bounds, doubled row endpoints, signed pool offsets and pixel +bounds. Files are capped at 32 MiB; VSWAP at 4096 pages. All allocations use the +existing 64 MiB payload-budget memory manager. Owners are stable handles; +world exit frees map/page caches without invalidating graphics/menu caches. +Unconfigured data-directory access fails instead of falling back to filesystem +root. All archive access is read-only and supports the existing case resolver. + +## Tests and results + +- CART GCC/C11 builds with the configured strict warnings and no new warnings; + the math library is added to the platform link configuration. No CART source + changes were necessary. Repeat builds report up to date. +- Twenty-eight unittest cases pass, including the prior graphics/menu/input/ + memory/Git tests, with ASan/UBSan on the application and C tests. The reused + SDL static archive itself is not instrumented. +- Synthetic maps, fonts, pictures, VSWAP pages and post streams are generated + temporarily by `tests/game_fixtures.py`. `game_tests.c` covers escaped tags, + near/far overlap, truncation/overruns, malformed map/plane data and spawn/wall + semantics, page boundaries/layout, signed sprite offsets, fixed-point extrema, + cardinal/door ray hits, scaler samples, collision/sliding, running/turning/ + strafing, door timers/occupancy/locks and coarse/fine 70 Hz scheduling. +- `game_sdl_tests.c` drives New Game through actual SDL key events, then tests + motion, quick taps, focus loss and simultaneous Escape/Enter returning safely + to the menu. Invalid-level tests keep the original menu usable with New Game + disabled. No synthetic success/gameplay screen replaces a failed load. +- Original Steam data loads in place. The decoded spawn is (29,57), angle 0 + (east). Integration walked through the original normal door at x=32 to + (34,57); SDL captures at spawn and beyond the cell were visually inspected. +- An independent Python decoder matches all three real map planes and a wall + page byte for byte. Every non-sparse Steam sprite page also passes bounded + post decoding. The previous title/framebuffer/palette oracle still passes. +- All 23 active C modules pass MinGW C11 compile-only checks with warnings as + errors. Native Windows linking/execution remains unverified. +- CART's SDL3 (including raylib/Android fixtures), output-directory, Android + profile/icon and Linux macro regressions pass. Existing icon-copy warnings + are unchanged. CART's pre-existing working-tree modifications were preserved. +- Whitespace, unchanged-original-source, Git safeguards and commercial-data/ + capture ignore checks pass. No data, fixture binaries or captures are added + to Git. No commits, pushes, SDK downloads or Ironclaw changes were performed. + +See [BUILD.md](BUILD.md) for reproducible normal/sanitizer commands. New tests +are in `game_tests.c`, `game_sdl_tests.c`, `game_fixtures.py` and the expanded +`test_engine.py`; existing frontend/video/Git tests remain active. + +## Remaining original-engine work + +Enemies and static objects are neither rendered nor collided with yet. Sprite +pages decode, but `DrawScaleds`/`ScaleShape`, actor state, combat, weapons, +pickups, keys and damage still need porting. HUD numerical fields are not +updated; only the original status artwork/play border are shown. No secret +pushwalls, elevator/exit progression, episode/difficulty flow, other playable +maps, saving/loading, demos or audio are claimed. Escape discards this level +session. Earlier UI animation/RNG omissions remain as documented in milestone 3. + +DOS-reference captures and recorded traces are still needed for a formal +pixel/gameplay parity claim, particularly old Borland floating-point table +rounding and variable-tic batches. Current evidence establishes the direct +source translation, original data compatibility, original wall presentation, +wall/door collision and deterministic movement slice. Next port the original +static/sprite renderer and actor dependencies, then combat and progression. diff --git a/docs/MILESTONE5.md b/docs/MILESTONE5.md new file mode 100644 index 00000000..04089db7 --- /dev/null +++ b/docs/MILESTONE5.md @@ -0,0 +1,152 @@ +# Milestone 5: E1M1 sprites, enemies and combat + +E1M1 now has original static objects, guards and dogs, directional sprites, +original enemy state machines, shooting, damage, pickups, weapon animation, +live status graphics, palette flashes and death/life restarts. New Game starts +E1M1 at the original medium difficulty. Escape ends the session and returns to +the menu. This is a playable combat slice, not a complete campaign port. + +## Build, run and controls + +From `~/Sync/git/wolf3d-revive`, using the current CART executable and the +existing SDL3 SDK in the sibling CART checkout: + +```sh +./build/tools/cart build --profile cart-sdl +./build/tools/cart run --profile cart-sdl -- \ + --data "$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" +``` + +Press a key at the title, then Enter on New Game. To start directly: + +```sh +./build/tools/cart run --profile cart-sdl -- \ + --data "$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" --level +``` + +| Keys | Action | +| --- | --- | +| Up / Down | Forward / backward | +| Left / Right | Turn | +| Alt + Left / Right | Strafe | +| Shift | Run | +| Ctrl (either side) | Attack; release between pistol/knife attacks | +| 1 / 2 / 3 / 4 | Knife / pistol / machine gun / chaingun, when available | +| Space | Operate adjacent door; matching keys unlock locked doors | +| Escape | End this game and return to the menu | + +Automatic weapons repeat while Ctrl is held. Guns require ammunition; the +knife remains available when ammunition runs out. Items are collected using +the original projected getting-distance test, subject to original health, +ammunition and gib eligibility limits. Escape does not save or pause a game. + +Existing `--check-assets`, `--check-ui`, `--check-level`, `--menu`, `--frames N`, +`--capture FILE.bmp` and `--help` options remain supported. `--check-level` +validates maps, wall pages, available sprite streams, normal-enemy animation +frames, weapon frames, static sprites, the initial HUD and scene without SDL. +Malformed data disables New Game, or reports an error for a direct level/check +request. The owned Steam directory is read only; no assets are staged. + +## Changes and original-source references + +| Phase / files | Ported functionality | +| --- | --- | +| A: `WL_ACT1.c`, `WL_AGENT.c`, `tests/game_tests.c` | Closing-door checks now use the complete inclusive player collision square, including corners outside the door's center row/column. They also protect shootable actors' physical bounds and reserved destination tiles. Closing reopens immediately when occupied. Both orientations, all corners, just-outside positions and entry during closing are tested. Static and live-actor collision augment the original player square and axis-slide order. | +| B: `WL_DRAW.c`, `WL_SCALE.c`, `WL_SPRITES.h` | Original `TransformActor`, `TransformTile`, `CalcRotate`, `DrawScaleds`, `ScaleShape` and `SimpleScaleShape` calculations from `WL_DRAW.C`/`WL_SCALE.C`, with sprite indices from `WL_DEF.H`. Signed-magnitude rotation, actor/tile forward biases, perspective height, eight facing frames/two pain directions, ray visibility, original visible-list limit and stable back-to-front height sorting remain. Transparent post masks preserve opaque palette index zero. Original scaler directory quantization and separately anchored left/right halves are retained, including asymmetric knife frames. Wall heights include original wide-post reuse and clip sprites per column. | +| B/C: `WL_OBJECT.c`, `WL_GAME.c`, `WL_ACTOR.h`, `WL_DEF.h` | Original `statinfo`, `SpawnStatic`, `PlaceItemType`, `ScanInfoPlane`, `SpawnNewObj`, stand/patrol spawning and original medium difficulty filtering. Bounded pools hold 150 actors and 400 statics. Integer-tagged DOS `actorat` entries become separate wall/static arrays and genuine actor pointers. Actor destinations, diagonal side checks, door waiting, area numbers and ambush neighbour priority follow the original. The small area graph is rebuilt from door states instead of maintaining pointer-dependent connection counters; opening connects on its first advancing tic, closing disconnects only at fully closed. | +| C: `WL_STATE.c`, `ID_US_A.c`, `ID_US_1.h` | Original guard/dog state tables and the common officer/SS/mutant tables from `WL_ACT2.C`; `DoActor` action/think/transition ordering from `WL_PLAY.C`; `TryWalk`, `MoveObj`, `SelectDodgeDir`, `SelectChaseDir`, `SelectPathDir`, `CheckLine`, `CheckSight`, `SightPlayer`, `FirstSighting`, `T_Stand`, `T_Path`, `T_Chase`, `T_DogChase`, `T_Shoot`, `T_Bite`, `DamageActor` and `KillActor`. Original speeds, reaction delays, ambush/hearing rules, attack probabilities, shot-distance rules, pain/death frames and drops remain. The 256-entry `ID_US_A.ASM` RNG preserves increment-before-read and byte wrapping. Audio calls are omitted, while guard death-sound selection still consumes its original RNG draw. | +| D/E: `WL_COMBAT.c`, `WL_PALETTE.c`, `WL_PLAY.c` | `WL_AGENT.C` knife/gun target selection, damage, surprise multiplier, original `attackinfo`/`T_Attack` timing, semi-automatic and held automatic fire, ammunition, weapon selection, health/ammo/treasure/key pickups, extra lives and drops. `LatchNumber`/status coordinates, weapon/key artwork, health-dependent faces, look animation and chaingun pickup face use original pictures. `WL_PLAY.C` red/white DAC interpolation, intensity/duration and red-over-white priority are retained. HUD drawing caches unchanged status. | +| E: `WL_PLAY.c`, `WL_MAIN.c` | `WL_GAME.C:Died` attacker-facing rotation at two degrees/tic, weapon removal, `ID_VH.C:FizzleFade` 17-bit LFSR red wipe, input/wait and life decrement, followed by E1M1 restart with pistol/8 rounds/100 health/no keys. Score restores to this level's entry value, zero; the extra-life threshold persists. After lives reach -1, the existing scores screen is shown and a key returns to the menu. The death flow is incremental and keeps the SDL event loop responsive. | +| Validation: `ID_PM.c/.h`, tests | Page-presence queries distinguish legal sparse directory entries from missing required frames. Startup validates sprite streams beyond the initial room, common enemy animation frames and all four weapons. New synthetic archives cover object spawning and full sprite-index ranges without commercial bytes. Malformed streams, missing offscreen frames, overfull pools and invalid spawns are rejected. | +| Integration/docs: `src/main.c`, `cart.toml`, `docs/BUILD.md`, `docs/PORTING.md` | Updated help, diagnostics, current build scope and commands. CART configuration/backend/dependencies are unchanged; only its introductory comment changes. | + +`WOLFSRC/` is untouched. This work does not import Wolf4SDL, wolf3d-lib or +wolf3d-portable code. Platform SDL3 video/input/timing remain isolated in +`src/platform/`; the engine adds no SDL dependency. No CART source changes, +new dependencies, commits or pushes were made. + +## Rendering and timing review + +The original quadrant stepping, half-angle tangent table, focal point, +signed-magnitude `FixedByFrac`, wall/door texture offsets, projection numerator, +scaler quantization and wide-post optimization were reviewed against +`WL_DR_A.ASM`, `WL_DRAW.C`, `WL_SCALE.C` and `WL_MAIN.C`. Existing exact ray and +wall-source-run regression checks still pass. Sprite scaling emits the original +source-pixel runs instead of executable x86 scaler code. Its clipping checks +each destination column instead of VGA mask/edge shortcuts; partial occlusion +at irregular wall edges may differ from those original shortcuts. No +pixel-perfect comparison against a running DOS executable is claimed. + +Simulation uses one-tic steps at 70 Hz, independently of SDL presentations. +Each simulation tic refreshes visibility and projected targets, collects items +and updates the framebuffer; unchanged presentations still avoid texture +uploads through the existing video path. Batched ticks and individual ticks +produce the same tested movement, actor states and inventory for identical +input. Fast make/break edges survive until a tic consumes them. Pauses discard +elapsed time above MAXTICS (10) rather than simulating an unbounded backlog. + +DOS used variable-size tic batches. Its per-frame RNG calls and probabilistic +AI can therefore produce a different sequence from this fixed-tic loop. Normal play seeds the original RNG from the low clock byte at game start +and life restart, using monotonic tics in place of the DOS BIOS clock. Asset +validation explicitly seeds zero, and tests supply deterministic start tics. The +original state machine and random table are used, not substitute enemy AI. +The fizzle retains the original `64000/70` candidate pixels per tic and full +LFSR traversal; it is not shortened to an arbitrary 70 presented frames. Its +writes are bounded to the actual viewport, fixing original border overdraw. + +## Verification + +```sh +WOLF3D_DATA="$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" \ + python3 -m unittest discover -s tests -v +``` + +- CART `cart-sdl` Linux build passes with GCC/C11 and strict warnings. +- 31 Python regression cases pass, including strict `-Werror` C executables. + `tests/combat_tests.c` covers projection, transparency, opaque zero, + asymmetric anchors, sorting/occlusion, medium spawns, blocking objects, + pickups/caps, RNG wrapping, reaction/ambush/hearing, area connectivity, + chase/shoot/death transitions, patrol arrows, dog bites, collisions, drops, + knife/pistol/automatic timing, ammo, selection, HUD, palette flashes, + per-tic/batched determinism, life restarts, game-over/menu and 1,000 mutated + sprite streams with output canaries. +- SDL event regression covers both Ctrl aliases, held pistol behaviour, quick + taps, focus loss, movement and game/menu transitions. Existing palette, + nearest-neighbour/aspect readback, repeated startup/shutdown, fonts, fades, + malformed archives, memory ownership and upstream-push protection pass. +- ASan/UBSan instrumented app and C tests pass the same suite with owned Steam + data. The reused SDL static archive itself is not instrumented. +- All 28 C modules pass strict MinGW C11 compile-only checks. Windows linking + and runtime remain unverified without a Windows SDL SDK. +- CART SDL3, Android icon/profile, Android ads generation, desktop directory + and Linux macro regression scripts pass. No Android device run is claimed. +- Owned Steam E1M1 validates 436 sprite pages, 20 medium-difficulty enemies, + one corpse, 121 static objects and 23 treasure objects. An aimed pistol + combat regression kills an original guard through real input/tics and + verifies ammunition consumption and scoring. This test positions the + player in a valid visible location; it is not a complete level playthrough. +- Native SDL captures of the start room and a guard/table scene were inspected + locally: original textures, directional actor, decor, weapon, occlusion and + HUD appear correctly. Captures remain in ignored `build/checks/`; none are + embedded here or added to Git. The commercial files were only read in place. + +The sanitizer compile/link command is in [BUILD.md](BUILD.md). Automated +fixtures contain synthetic graphics/map/sprite bytes only. + +## Remaining work + +- Audio/music, elevator/level completion, secret pushwalls, campaign + progression, save/load, demos and episode/difficulty selection remain + unavailable. E1M1 is the only launched level; no completion is simulated. +- The post-game scores display uses the existing table. Original qualifying + high-score name entry/persistence is not ported. There is no invented + game-over success screen. +- Audio-dependent face/sound timing remains to be integrated with the + original sound manager. Other levels/bosses are not + claimed to work merely because common enemy state tables are present. +- Life restart redraws the initial scene directly; the original initial + level fizzle-in/preload presentation is not yet ported. Death rotation, + red fizzle and wait/life reset are implemented. +- No complete E1M1 playthrough or DOS screenshot/recording equivalence test + has been performed. Testing establishes this combat slice and its stated + rules, not complete Wolfenstein 3D compatibility. diff --git a/docs/MILESTONE6.md b/docs/MILESTONE6.md new file mode 100644 index 00000000..025486b0 --- /dev/null +++ b/docs/MILESTONE6.md @@ -0,0 +1,201 @@ +# Milestone 6 — first implementation pass: normal-level progression + +Subsequent work: [Milestone 6C](MILESTONE6C.md) implements six-slot save/load, +pause/resume and animated intermission counters/sounds. Historical remaining-work +notes below describe the state at this report's milestone. + +## Current status after Milestone 6A Part 2 + +All original bosses, required projectiles and all six episode completion +paths are implemented. Owned-data validation now loads/renders/simulates +**all 60 maps at all four difficulties (240/240 combinations)**. Controlled +SDL weapon fights exercise every finale, Mecha Hitler's transformation, +cinematics, original statistics/articles and return through scores to menu. +See [MILESTONE6A.md](MILESTONE6A.md) for source references, test results, +differences and limitations. [Milestone 6B](MILESTONE6B.md) adds native SDL3 +music and effects; see that report for audio verification and remaining limits. +Full navigated playthroughs and saves remain outstanding. The remainder records the earlier Milestone 6 pass and +its original 51-map baseline, not the current actor/finale support. + +2026-11-02. This is an incremental, working gameplay/progression slice, **not +completion of Milestone 6 or of the original game**. Audio, saving/loading, +boss/ghost/victory actors and several desktop features remain unimplemented. + +## Baseline review + +The checkout already contained uncommitted Milestone 5 changes and untracked +source/tests/documentation. They were preserved; no reset, commit or push was +performed. Before this pass, the CART Linux build and all 31 existing Python +regressions passed with owned Steam data. The implementation was inspected +alongside `WOLFSRC/`, rather than inferred from the milestone document. + +Verified existing functionality includes E1M1 maps/textures/sprites, normal +enemy state machines, weapons/combat/pickups, health/ammo/lives/score/keys/HUD, +doors, the original RNG table, palette shifts, death/life restarts and game +over returning through the scores page. Launch remained restricted to E1M1; +pushwalls, elevators, intermissions, selection, audio and saves were absent. +Milestone 5's stated scope was substantially accurate; normal-enemy state +tables existed for mutants but the map scanner never spawned them. + +## What this pass implements + +- New Game opens six original episode choices and four original difficulty + choices. Arrows select, Enter/Space confirms, Escape returns one page. The + original episode pictures, skill pictures and menu fonts are used. Choices + persist while navigating the control panel. `--level` retains its E1M1, + medium-difficulty direct-start behavior. +- Map selection uses `episode * 10 + mapon`. Ordinary levels preserve health, + ammunition, weapons, score, lives and extra-life thresholds. Keys and level + counters reset at the next floor. The HUD displays the current floor. +- Normal guard/officer/SS/dog difficulty bands are decoded individually; + mutant stand/patrol codes and both mutant difficulty bands now work. Mutant + health is 45/55/55/65; other normal enemy health remains original. Baby + difficulty quarters incoming damage. Existing original AI/state tables and + combat algorithms are reused, with no alternate gameplay engine. +- Space operates a tile-21 elevator only when facing east/west, changes its + switch texture and ends the floor. Raw area tile 107 selects a secret exit. + Normal exits advance one floor; secret exits select floor ten. Return floors + are the original `{1,1,7,3,5,3}` zero-based episode table. +- Intermissions show original artwork, time, par, kill/secret/treasure ratios + and the final bonus. All 48 ordinary-floor par times are ported. Time is + counted in simulation tics at 70 Hz. Integer percentage truncation, zero + totals yielding zero percent, 500 points per second under par, 10,000 per + perfect ratio and the secret-floor 15,000 bonus match the original. Bonuses + are awarded once, including normal extra-life handling. Ratios for the + eight ordinary floors are retained in memory. Acknowledgement loads the + next floor without simulating time spent on the intermission. +- Secret pushwalls reserve destination cells, block actors, count secrets, + clear their consumed markers, move in four cardinal directions, stop after + two tiles or one tile when blocked, and expose the player's area in newly + cleared cells. Only one wall moves at a time. Wall/static/actor occupancy + prevents a blocked push. The renderer ports the original partial intercept, + texture selection/flips and 0..63 wall position; moving walls are not doors. + Runtime marker/area arrays retain immutable cached map planes for restart. +- Death on a later floor restarts that floor, restores its entry score and + resets health/ammo/keys/weapons according to the original Died flow. It + retains the decremented lives and existing extra-life threshold. +- Maps requiring unported bosses, ghosts or victory actors fail explicitly. + A failed initial/next-floor load displays its reason, releases level/page + resources and returns to the menu on acknowledgement. Encounters are not + removed or replaced with normal enemies to make a map appear supported. + +## Source references and adaptations + +`WOLFSRC/` remains unchanged. New/extended engine code is derived from: + +| Original source | Runtime implementation | +| --- | --- | +| `WL_MAIN.C:NewGame`, `WL_GAME.C:SetupGameLevel`, `ScanInfoPlane`, `GameLoop`, `Died`, `ElevatorBackTo` | `WL_GAME.c`, `WL_OBJECT.c`, `WL_PLAY.c`: selection, per-level reset, inventory/entry score, progression and restart. | +| `WL_ACT2.C:starthitpoints`, `SpawnStand`, `SpawnPatrol`; `WL_AGENT.C:TakeDamage` | `WL_OBJECT.c`, `WL_COMBAT.c`: difficulty filtering, mutant spawning/health, baby damage. Existing normal-enemy state machines remain in `WL_STATE.c`. | +| `WL_AGENT.C:Cmd_Use`; `WL_ACT1.C:PushWall`, `MovePWalls` | `WL_ACT1.c`, `WL_PLAY.c`: cardinal interaction, elevator state and one-tic wall motion. | +| `WL_DR_A.ASM:vertpushwall`, `horizpushwall`; `WL_DRAW.C:HitVertPWall`, `HitHorizPWall` | `WL_DRAW.c`: moving-wall intersections, projected distance, source columns and texture pages. | +| `WL_INTER.C:LevelCompleted`, `Write` | `WL_INTER.c`: original par times, arithmetic and result artwork. | +| `WL_MENU.C:CP_NewGame`, `DrawNewEpisode`, `DrawNewGame` | `WL_MENU.c`, `WL_MAIN.c`: resumable selection pages integrated with the existing SDL event loop/fades. | + +The intermission currently takes the original immediate-final-results path. +Animated counting, BJ breathing, sounds and transition/preload presentation +are still outstanding. It does not claim the full original intermission +presentation. High-score name entry/persistence and episode endings remain +unported. + +The earlier fixed one-tic simulation is retained. For pushwalls, the original +`pwallstate > 256` completion check becomes `>= 256`: fixed one-tic steps can +land exactly on 256, whereas the original multi-tic loop normally overshot +it. Without this adaptation a one-tic loop incorrectly moves a third tile. +The state starts at one, crosses tiles at 128 and 256 and retains original +half-tic texture-position quantization. Simulation remains independent of +presentation. Milestone 5's documented DOS variable-tic/RNG sequence +limitations still apply; no DOS recording/pixel-perfect equivalence is claimed. + +Checking every Steam map found assumptions that only held for E1M1: + +- E1M3 has unused outer-edge floor. Validate enclosure of initially reachable + floor/doors, rather than require every boundary cell to be a wall. Ray and + movement bounds remain checked. Pushwalls may occupy a boundary cell, but + cannot reserve outside the map. +- E2M3 has floor at a door jamb. Original SpawnDoor marks it `0x40`; preserve + movement through the floor and the original wall-table-zero/jamb rendering. +- E4M2 has a static object inside a wall; the original scanner permits this. +- E5M4 has overlapping patrol destination reservations; original scan order + decides which pointer owns the cell while both actors remain in the list. +- E4M6 on hard reserves a closed door as an initial patrol destination. + Original SpawnPatrol reserves that first move unconditionally. + +Tests that incorrectly labeled the first three applicable synthetic patterns +as corrupt were corrected and replaced with positive compatibility regressions. +Pool limits, invalid spawns, malformed streams, movement bounds, reachable +perimeter escapes and required sprite validation remain covered. + +## Build and verification + +```sh +./build/tools/cart build --profile cart-sdl +WOLF3D_DATA="$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" \ + python3 -m unittest discover -s tests -v +``` + +- CART Linux build passes with portable C11 and the existing SDL3 SDK. No + dependencies were added and no CART source/configuration changes were + needed for this pass. +- CART SDL3 and desktop output-directory regression scripts pass. +- 37 Python regression cases pass, including strict `-Werror` C executables. + New `campaign_tests.c` covers episode/difficulty values, normal and mutant + spawns, baby damage, ratios/bonuses/timing, all secret return routes, + inventory/door reset across levels, later-floor death restart, four-way + pushwalls, blocked pushes, one-/two-tile stops and moving-wall ray distances. + Existing AI/combat, RNG, timing, archives, input, video and Git safety tests + continue to pass. +- SDL tests exercise episode/skill cancellation and selection, choose E2 on + hard, operate a pushwall and elevator, acknowledge an intermission, load the + next floor, and verify that a missing next map reports an error and returns + to the menu. Synthetic tests use SDL dummy video/software rendering. +- All 60 owned Steam maps were checked at all four difficulties: **51 maps + load/render at every difficulty (204 combinations); nine are explicitly + rejected at every difficulty (36 combinations).** This validates decoding, + spawning, sprite streams and initial rendering, not complete playthroughs. +- Native Linux SDL software-renderer checks with owned Steam files passed + selection, an E1M1 pushwall, an elevator intermission and E1M2 loading. + Captures of selection, skill, E2M1, the moving/opened secret, intermission + and E1M2 were visually inspected in ignored `build/checks/`. The scripted + check positions the player beside real secret/elevator tiles; it does not + navigate the full level. Commercial files were read only, never staged. +- ASan/UBSan app and C tests pass the suite with owned Steam files, including + resource ownership checks (`MM_TotalBytes() == 0`) after shutdown. The + existing static SDL archive is not sanitizer-instrumented. See `BUILD.md` + for the combined sanitizer compile/link command. +- All 28 application C translation units pass strict MinGW C11 compile-only + checks with SDL3 headers. Windows linking/runtime, fullscreen transitions + and native Windows resource behavior remain unverified. + +The unsupported maps in the owned WL6 installation are E1M9, E2M8, E2M9, +E3M9, E3M10, E4M9, E5M9, E6M9 and E6M10. Consequently no episode can yet be +completed. No unsupported map is skipped automatically. + +## Outstanding Milestone 6 work + +1. Port boss/ghost/projectile/victory actors and their exact states/actions, + boss keys, death cameras, BJ victory movement and episode endings. Verify + actual playthroughs of all six episodes, including secrets and boss maps. +2. Implement the original sound manager with SDL3 output, a small compatible + licensed OPL emulator, AdLib music, digitized effects, original sound + priorities/timing/positioning and independent music/effects volumes. + **There is still no audio initialization, playback or audio cleanup test.** +3. Implement versioned, pointer-free saves, multiple slots, save/load menus, + complete actor/door/pushwall/RNG/inventory restoration, corruption rejection + and persistence tests. There is no save/resume or quick save/load yet. +4. Add the small portable C11/TOML game configuration foundation and functional + Classic/Enhanced settings. `cart.toml` remains build configuration only. + No nonfunctional settings/menu rows were enabled. +5. Add automatic Steam asset discovery and keep `--data` as an override. + Currently `--data` is required. Missing archives retain existing clear + errors. Fullscreen/window switching and its tests remain to be added; + existing SDL windowed 4:3 presentation remains in use. +6. Restore original demo playback where practical, score entry/persistence, + full intermission animation/audio and initial-level transitions. Compare + gameplay/render/timing behavior with the DOS original. +7. Link/package/test through CART with a Windows SDL SDK on Windows, and run + actual desktop/fullscreen/audio lifecycle tests on both supported systems. + +No game-specific behavior was added to CART, no Ironclaw files were modified, +no commercial assets were bundled, and no Git history or original copyright +and licensing notices were changed. No commit or push was made. diff --git a/docs/MILESTONE6A.md b/docs/MILESTONE6A.md new file mode 100644 index 00000000..4f96e491 --- /dev/null +++ b/docs/MILESTONE6A.md @@ -0,0 +1,269 @@ +# Milestone 6A — original campaign actors and completion + +Subsequent work: [Milestone 6C](MILESTONE6C.md) implements six-slot save/load, +pause/resume and animated intermission counters/sounds. Historical remaining-work +notes below describe the state at this report's milestone. + +2026-11-02. All original bosses, required projectiles and the six episode +completion paths are implemented. **All 60 owned WL6 maps load, render and +simulate at all four difficulties: 240/240 combinations.** Controlled SDL +weapon fights exercise all six finales, their statistics, both original +ending pages, scores and return to the menu. + +This is not a claim of six fully navigated episode playthroughs, DOS demo +compatibility or pixel-perfect equivalence. The controlled tests reposition +the player and refresh health/ammunition; their exact limits are below. +Audio playback, save/load and Enhanced Mode remain outside this milestone. +Subsequent [Milestone 6B](MILESTONE6B.md) implements native music/effects and +restores the original logical sound-mode boss delays; its report supersedes +this milestone's audio-off timing limitation. + +## Baseline and source provenance + +Part 1 added Hans, Gretel and four ghosts: 54 maps / 216 combinations and 42 +Python regressions passed. Part 2 began from a clean checkout and reproduced +that build and test baseline before editing. Milestones 5, 6, the Part 1 +report, PORTING.md, BUILD.md, the active engine and original source were +reviewed. Existing rendering, combat, movement, doors, pushwalls, selection, +intermissions, inventory and RNG were extended. + +All gameplay references are id Software's original `WOLFSRC/`, which remains +unchanged. New engine/tests retain GPL-2.0-only notices and source attribution; +see [LICENSING.md](LICENSING.md). No third-party port or dependency was added. +Commercial assets are read from the owned Steam directory, never staged or +bundled. No CART or Ironclaw files, commits or pushes were made. Upstream's +push URL remains `DISABLED`. + +## Episode finale status + +Display floor numbers are one-based; absolute map indices are zero-based. +Each row is covered by the owned SDL weapon/completion regression. + +| Episode finale | Absolute map | Boss encounters | Completion | Verified result | +| --- | --- | --- | --- | --- | +| E1M9 | 8 | Hans Grosse | Gold key, exit tile, BJ run/jump/yell | Statistics, both ending pages, scores, menu | +| E2M9 | 18 | Dr. Schabbs | Needle fight, death camera/replay | Statistics, both ending pages, scores, menu | +| E3M9 | 28 | Five Fake Hitlers, Mecha Hitler, Hitler | Flames, mecha corpse and inherited Hitler actor, death camera/replay | Statistics, both ending pages, scores, menu | +| E4M9 | 38 | Giftmacher | Rockets, death camera/replay | Statistics, both ending pages, scores, menu | +| E5M9 | 48 | Gretel Grosse | Gold key, exit tile, BJ run/jump/yell | Statistics, both ending pages, scores, menu | +| E6M9 | 58 | General Fettgesicht | Rocket plus gun burst, death camera/replay | Statistics, both ending pages, scores, menu | + +The E3 SDL fight verifies weapon-driven Mecha-to-Hitler completion in the +original map containing all five Fake Hitlers. Fake Hitler's health, +specialized thinker, eight-flame burst and flame collision are also covered +separately by synthetic tests; the SDL test does not require killing every +Fake Hitler before the final boss, nor does the original victory condition. +No encounter or victory marker is removed, replaced or skipped for map +validation. Loading a finale does not automatically complete it. + +## Ported functions and rules + +### Actors and combat + +`WL_ACT2.C` supplies the complete non-SPEAR state tables for Hans, Gretel, +Schabbs, Giftmacher, Fettgesicht, Fake Hitler, Mecha Hitler, Hitler, the four +ghosts, needles, flames, rockets, smoke, explosions and BJ. Tests compare all +46 Part 1 definitions and all 139 Part 2 definitions directly with DOS source, +including shapes, rotation, tics, thinkers, actions and successors. + +Original spawn codes are 214 (Hans), 197 (Gretel), 196 (Schabbs), 215 (Gift), +179 (Fettgesicht), 160 (Fake Hitler), 178 (Mecha Hitler), and 224–227 +(Blinky/Clyde/Pinky/Inky). Initial facing, ambush/shootable flags and the +four-difficulty health tables are retained. Hitler after transformation has +500/700/800/900 health. Ghost spawning intentionally does not assign health +or shootability, despite the unused ghost hit-point table entries. + +Ported/extended routines include `SpawnBoss`, `SpawnGretel`, `SpawnGhosts`, +`SpawnSchabbs`, `SpawnGift`, `SpawnFat`, `SpawnFakeHitler`, `SpawnHitler`, +`FirstSighting`, `SightPlayer`, `T_Chase`, `T_Schabb`, `T_Gift`, `T_Fat`, +`T_Fake`, `SelectRunDir`, `DamageActor`, `KillActor`, `A_HitlerMorph`, +`A_MechaSound` and `A_Slurpie`. Shared algorithms remain from `WL_STATE.C` and +`WL_AGENT.C`. Specialized dodge/flee/attack logic is not replaced by guard AI. + +Hans retains his shot-distance accuracy advantage; Gretel uses the original +ordinary shot calculation. Boss burst lengths, damage, score and drops +remain original. Fake Hitler awards 2,000 points, other bosses 5,000, and +Hans/Gretel drop the gold key. Mecha's death leaves its corpse and spawns the +original Hitler state at its physical position, inheriting distance, +direction and flags and consuming the original initial-state RNG draw. +Mecha and Hitler each award their original points/kill count; no extra +`killtotal` is invented for the transformation. + +### Projectiles and actor ownership + +`T_SchabbThrow`, `T_GiftThrow`, `T_FakeFire`, `T_Projectile`, +`ProjectileTryMove` and `A_Smoke` retain original targeting, speed, +original float angle quantization, signed-magnitude fixed-point movement, +wall/static/door collision, strict +player-hit square, damage RNG and state transitions. Needles/rockets move at +`0x2000`; flames at `0x1200` on state actions, rather than every tic. Rockets +emit smoke and explode on walls. Player hits remove the projectile, as in +DOS; no invented explosion splash damage is added. Rocket rotation uses its +angle rather than its `nodir` direction. + +`WL_PLAY.C:GetNewActor/RemoveObj` is adapted to the existing bounded array +and original linked iteration order. Runtime objects append to the live +list for simulation and drawing; removed projectile/effect slots are reusable. +Patrol spawning releases its birth-cell mark before reserving its first move. Array `objcount` is a +high-water mark, not a live-object count. Pool exhaustion reports an error +through the existing game-error/menu path, replacing the original fatal +`Quit`, without corrupting the list or silently losing a required morph. +The killer's position is snapshotted before its projectile slot can be reused. + +### Victory, cameras and progression + +`WL_AGENT.C:VictoryTile/VictorySpin` and `WL_ACT2.C:SpawnBJVictory`, +`T_BJRun`, `T_BJJump`, `T_BJYell`, `T_BJDone`, `A_StartDeathCam` and +`CheckPosition` are ported into resumed, bounded steps. Exit-plane code 99 +is recognized as a movement trigger. BJ runs the original six path choices, +jumps, yells, waits in the final frame and sets `ex_victorious`. + +Death cameras preserve the initial 100-tic hold, grey fizzle, original message, +300-tic acknowledgement timeout, original angle/position search, death-state +replay and final 100-tic hold. Grey and viewport replay fizzles use the +original 70- and 20-frame candidate budgets and LFSR respectively. Their +bounded full traversals take 144 and 41 simulation tics. The unacknowledged +initial camera setup therefore takes 585 tics. The blinking original +`SPR_DEATHCAM` overlay uses a replay counter following the original +post-fizzle clock reset. Cinematic input cannot move/use/fire, and a death +camera does not run BJ's spin or consume face-look RNG. + +`WL_INTER.C:Victory` draws the original victory artwork, eight-floor average +ratios, summed time, 99:99 clamp and medium/hard verification code. The HUD +retains the final score. `WL_TEXT.C:EndText/ShowArticle/PageLayout` renders the +actual six external end articles with original artwork, colors, word wrapping, +picture margins, borders and page numbering. Arrows, Enter and Page Up/Down +navigate; Escape closes the article, followed by scores and menu. + +`GameStep` distinguishes ordinary/secret exits, boss/BJ victory and player +death/restart. `NextMap` never maps a finale to another episode or the secret +floor; finale victory is handled separately. Existing secret-floor return +routes `{1,1,7,3,5,3}`, ordinary inventory carry, key reset, bonuses and +same-floor death restart remain tested. All 60 original per-map ceiling +colors are now selected from `WL_DRAW.C:vgaCeiling`. + +### Sound and RNG + +The existing synchronous sound-event hook now includes original new boss +sight/death/attack sounds, mecha footsteps, slurpie, projectile launch/impact +and BJ yell. Original non-positional boss sounds use NULL actor. No SDL audio +backend is initialized. Hook consumers must not retain actor pointers or +mutate simulation. + +Registered WL6 death-scream selection still consumes its original RNG even +without a sink, including the rare extra draw on **absolute map index 9, +E1M10**, rather than every episode's secret floor. Original Schabbs/Hitler +immediate death-sound calls and their later state actions remain. The four +sound-dependent boss `die2` delays use the original **digitized-audio-off +five tics**, consistent with the current audio-free profile; Milestone 6B +must restore the original 140-tic selection when digitized audio is enabled. + +## Files modified + +- New `src/engine/WL_ACT2.c/.h`: remaining boss/projectile states and routines, + fleeing, morph, effects and sprite requirements. +- New `src/engine/WL_VICTORY.c`: BJ, death-camera timing/placement, fizzle and + replay lifecycle. +- New `src/engine/WL_TEXT.c`: bounded original ending-article layout/navigation. +- `WL_OBJECT.c`, `WL_STATE.c`, `WL_ACTOR.h`, `WL_DEF.h`: spawning, actor + allocation/removal, enemy integration, sound events and required state data. +- `WL_AGENT.c`, `WL_COMBAT.c`, `WL_DRAW.c`: victory tiles, stable killer data, + rocket orientation, camera overlay and original map ceiling colors. +- `WL_PLAY.c`, `WL_GAME.c`, `WL_INTER.c`, `WL_MAIN.c`: cinematic/progression + flow, player control/RNG rules, original statistics and frontend return. +- New `tests/finale_tests.c`, `tests/finale_sdl_tests.c`; updated + `campaign_tests.c`, `combat_tests.c`, `game_fixtures.py`, `test_engine.py`. +- README, BUILD.md, PORTING.md, MILESTONE6.md and this report: verified scope. + +## Validation and playthrough coverage + +Commands are in [BUILD.md](BUILD.md): + +```sh +./build/tools/cart build --profile cart-sdl +WOLF3D_DATA="$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" \ + python3 -m unittest discover -s tests -v +``` + +Verified results on the final code: + +| Check | Result | +| --- | --- | +| CART `cart-sdl` Linux build | Pass | +| Standard owned-data Python/C/SDL suite | 45/45 pass | +| ASan/UBSan application and C tests, same owned-data suite | 45/45 pass; no sanitizer diagnostics | +| Owned map/difficulty sweep | 240/240 load, render and run 140 actor tics safely | +| Native Linux SDL software-renderer finale harness | All six medium-difficulty controlled weapon/completion paths pass | +| MinGW C11 strict compile-only checks | All 31 application modules pass | +| Source-table comparisons | All 185 special/projectile/victory definitions match the original static tables | +| Shutdown ownership checks and Git whitespace checks | Pass | + +The regression suite has 45 Python cases, including strict `-Werror` C tests. +The same suite passes with the combined ASan/UBSan application and C-test +procedure. The final sanitizer executable was built with the documented flags +as `build/checks/wolf3d-revive-part2-final-asan` and selected through +`WOLF3D_BINARY`. The reused SDL static archive itself is not instrumented. + +Coverage includes: + +- All 240 owned map/difficulty combinations: spawn, required sprite decoding, + initial render, 140 actor tics, periodic rendering and resource cleanup. +- All boss spawns/health/facing, source-table equality, specialized attacks, + flame emission cadence, projectile-wall/player/door/static collision, + original damage RNG and rocket effects/removal. +- Morph position/flags/distance/direction/health/RNG and preserved mecha + corpse; 1,000 effect-slot reuse cycles, exhaustion, killer-slot reuse, stable + sprite order after reuse and released patrol birth-cell reservations. +- All four death-camera bosses, exact hold/fizzle budgets, frozen camera and + input/RNG behavior, BJ animation/yell, all six articles and frontend return. +- Average-ratio truncation, total-time arithmetic/clamp and difficulty code, + death/restart on a boss floor, secret routes, missing boss/projectile/BJ/ + overlay sprites, malformed article headers/end markers and existing corrupt + maps/archives, limits, combat, input, rendering and Git safeguards. +- MinGW C11 compile-only checking for all 31 application modules. Windows + linking/runtime remain unverified without a Windows SDL SDK/runtime. + +**Controlled gameplay coverage:** `finale_sdl_tests.c` loads every owned finale +without removing actors. It opens nearby doors through the existing door API, +positions the player, aims and delivers actual SDL Ctrl input through the +existing chaingun/combat simulation at the original medium difficulty. +Health and ammunition are refreshed; spawn/health tests and the map sweep +cover all four difficulties. +It verifies boss death, the original Mecha-to-Hitler transition, collected gold +keys and exit tiles where applicable, complete cinematics, statistics, both +article pages, scores and menu. Initial floor ratios are zero in these tests +because preceding floors were not played. It does not claim those zero +statistics represent a full episode run. + +Native Linux desktop software-renderer checks use the same harness. Captures +of all six victory statistics and all twelve original ending pages were +visually inspected. Additional boss, morph and replay captures remain under +ignored `build/checks/milestone6a-part2/`; no commercial files are in Git. + +**No complete navigated floor or episode playthrough was performed.** Tests +establish controlled combat/completion paths and bounded simulation, not +unassisted player navigation through six campaigns. + +## Differences and remaining work + +- The established fixed one-tic 70 Hz loop remains. DOS variable-tic batching + can change probabilistic AI/RNG ordering. No DOS recording, bit-perfect, + demo-perfect or pixel-perfect equivalence is claimed. Existing ray/scaler + adaptations and original baseline caveats remain. +- Runtime pool exhaustion becomes a recoverable explicit game error. Killer + snapshots, bounded camera searches, sprite/map checks and clipped fizzle + writes replace unsafe DOS pointer/border behavior. +- The Part 1 ghost closed-door wait adaptation remains: a negative movement + distance waits through the existing door API instead of snapping through a + closed door. +- Internal statistics/article boundaries draw on the next frame instead of + reproducing every original palette fade. Existing intermissions still use + their immediate-final-results path; count-up/BJ breathing and initial-level + preload/fizzle presentation are not expanded here. +- Article layout targets the six registered WL6 end articles. They use page, + color and graphic commands. Bounded location/bar/comment commands are also + supported; timed-picture commands are rejected and are not present in any + of these six articles. This is not a generalized modding/text engine. +- Qualifying high-score name entry/persistence, audio/music, saves, demos, + Windows runtime verification and full navigated playthroughs remain. Audio + is Milestone 6B; save/load and Enhanced Mode remain later work. diff --git a/docs/MILESTONE6B.md b/docs/MILESTONE6B.md new file mode 100644 index 00000000..3616b9e0 --- /dev/null +++ b/docs/MILESTONE6B.md @@ -0,0 +1,246 @@ +# Milestone 6B — native SDL3 audio + +2026-11-02. Original WL6 music and effects now play directly from the player's +archives through a shared YM3812 synthesiser and SDL3. There is no converter, +PCM asset cache, extracted soundtrack or external playback process. The normal +application selects AdLib effects plus digitised voices, with independent music +and effects volume/mute controls in the existing Sound menu. + +This implements the core playback path and campaign integration. It does **not** +complete every presentation detail: the existing immediate-results intermission +still skips animated counting and its counting/percentage sound sequence. +Detailed listening comparisons against DOS and native Windows hardware playback +also remain outstanding. These limits are not covered by a claim of complete +original audio fidelity. + +## Baseline and provenance + +The working tree was clean. Before porting, the CART build and all 45 existing +regressions passed with owned Steam files. MILESTONE6A.md, MILESTONE6.md, +BUILD.md, LICENSING.md, sound identifiers/hooks, resource handling, SDL lifecycle +and original DOS routines were reviewed. `WOLFSRC/` remains unchanged. No CART +or Ironclaw source was changed, commercial assets added, commit made or push +performed. Upstream pushing remains disabled. + +Primary implementation references are the archived `ID_SD.C`, `ID_SD.H`, +`ID_SD_A.ASM`, `AUDIOWL6.H`, `WL_MAIN.C:InitDigiMap`, `WL_GAME.C:SetSoundLoc`, +`WL_PLAY.C:songs`, and original gameplay/menu sound call sites. + +## Synthesiser selection and licence + +[emu8950](https://github.com/digital-sound-antiques/emu8950) was selected at +commit `f82a22e80b68820f263084aa8506b12eb1c9b4dd`; the source labels itself +v1.2.3. It is a small C implementation with an explicit YM3812 mode, nine +channels, waveform selection, envelopes, feedback and rhythm/percussion. +Its [MIT licence](../third_party/emu8950/LICENSE) permits inclusion in this +GPL-2.0-only engine while preserving its notices. It compiles as C11. + +[Nuked-OPL3](https://github.com/nukeykt/Nuked-OPL3) was also reviewed. It is +C, self-contained, and LGPL-2.1-or-later according to its source notices, but +models YMF262/OPL3. emu8950 provides the explicit YM3812 target and per-channel +output gains needed here. This selection does not assert greater hardware +accuracy than Nuked. C++ DBOPL and large audio frameworks were not imported. + +Upstream files, exact provenance and two safety patches are recorded in +[README.wolf3d.md](../third_party/emu8950/README.wolf3d.md). The patches fix +partial-allocation cleanup and a negative signed left shift found by UBSan. +The unused Y8950 ADPCM module is linked because upstream references its API; +the selected chip type is YM3812 and no Y8950 sample playback is used. + +## Resources and ownership + +`ID_SD.c` uses the existing case-aware `CA_ReadDataFile` and stable MM ownership +handles. AUDIOHED's little-endian offsets bound the original 288 WL6 chunks: +87 PC sounds, 87 AdLib sounds, 87 unused sampled-sound slots, then 27 music +chunks. Actual effects use the original 87 `soundnames` indices and the AdLib +common header's priority. All effects validate their 32-bit length, 16-bit +priority, 16-byte instrument and block/data boundaries. PC chunks are validated +but PC speaker playback is not exposed or implemented. + +WL6 music uses the original length-prefixed `MusicGroup`, followed by four-byte +register/value/delay records. Length must be nonzero, divisible by four and +inside its archive chunk. This is deliberately a WL6 loader, not a generic +IMF type-0/type-1 detector. Empty unused digitised slots are allowed; malformed +referenced resources disable audio with an error rather than unchecked reads. + +VSWAP's complete offset/length directory is checked for file bounds, ordering +and sparse entries. The last page's original metadata supplies start-page and +byte length for each of 46 digitised samples. Samples are copied across bounded +4096-byte pages into ordinary memory. No dependence on the graphics page +cache survives a level restart. Mapping is the registered, non-SPEAR table, +including DEATHSCREAM2/3 sharing sample 13. No resource filesystem work occurs +while generating PCM. Archives are opened read-only; no game directory write +permission is needed. Existing CA startup still requires the original archive +set and rejects missing/empty files before the optional audio startup stage. + +## Scheduling and mixing + +The portable sound manager ports `SD_PlaySound`, AL instrument programming, +`SDL_ALSoundService`/DOFX, IMF sequencing, music off/start, digitised interruption +and priority handling. `SD_Render` advances a rational 700 Hz sample clock; +every fifth service tick processes 140 Hz effects **before** music, as in the +original ISR. At 44.1/48 kHz, register timing is independent of frame rate and +render request size. There is no change to the separate 70 Hz simulation. + +The sequencer preserves a subtle DOS rule: immediately after the final event +is written, its pointer and time counters reset; that final event's delay is +not waited out. Looping preserves live chip envelopes, instruments and rhythm +state. It does not reset the synthesiser or append an invented release tail. +Music transitions key off music channels and rhythm, matching `SD_MusicOff`. +Re-enabling music restarts the selected track and its instrument setup. + +A single chip receives both music and effects. Effects program operators zero +and three/channel zero, clear the instrument first, set connection to zero as +in Wolf's MUSE-compatible driver, and use the original block/key-on pattern. +IMF register writes can overwrite those registers. There are no independent +full-chip music/effect instances. Channel zero is assigned the effects gain; +remaining melodic and percussion outputs receive the music gain. Owned tracks +use channel zero for their initial reset, rather than melodic notes. This is +an output-level convenience, not separate synthesis or filtered IMF writes. + +The chip runs at its native approximately 49,716 Hz rate; bounded linear +interpolation produces the requested output rate without an allocating +resampler in the render path. Digitised samples are unsigned eight-bit PCM, +held at the original SB DAC rate: `1000000 / 142` Hz (about 7042.25 Hz), from +`256 - floor(1000000/7000)`. Their phase accumulator preserves that fractional +rate. The mixer combines FM and voices with saturation to stereo signed +16-bit PCM. Analogue AdLib/SB filters and exact DAC electrical behaviour are +not reproduced; this is not a cycle- or analogue-exact hardware claim. + +There is one AdLib effect and one digitised voice, with independent original +priorities. Lower priority cannot interrupt; equal or higher can. Neither +lane invents modern polyphony. The original 15-by-30 positioning tables, +focal camera offset, rotated coordinates, distance limits and non-positional +sounds are retained. Only digitised sounds use the original SB Pro position +attenuation. Original attenuation nibbles map to linear software gain; the +analogue mixer chip's exact gain curve is not modelled. Positions are copied, and moving the listener updates the active +sample's balance; removed/reused actors are never dereferenced by playback. + +## SDL3, settings and integration + +`sdl_audio.c` opens an SDL3 default playback stream, supplies 48 kHz stereo +PCM with `SDL_PutAudioStreamData`, and lets SDL convert to the physical device. +The main thread fills a bounded 24–32 ms queue in 384-frame blocks. SDL owns +asynchronous consumption. There is no application audio callback, mutex, +filesystem access, dynamic allocation or mutable actor access in synthesis. +Severe main-thread stalls can underrun this small queue; no underrun changes +the simulation, RNG or music's sample-domain tempo. + +Audio starts after video startup and stops before video's `SDL_Quit`. +Repeated startup/shutdown and failed opening release all resource handles. +A device/queue error reports a reason and permits silent play. SDL manages +its default-device routing. On Linux, if an ALSA-only SDL build cannot open +its unconfigured default and no user device hint exists, the backend also +tries ALSA's standard `pulse` endpoint without changing system configuration. +Other SDL drivers keep their normal default behaviour. + +The main Sound menu uses the existing fonts, panel renderer and input queue: +Up/Down select; Enter/Space or Left/Right toggle enable switches; Left/Right +change the corresponding volume in five-percent steps. Settings are session +only. `--no-audio` skips resource synthesis/device startup. No nonfunctional +PC speaker/device mode rows, new UI framework or configuration registry exist. + +Title/attract, control panel, scores, all 60 level selections, intermissions, +victory statistics and ending articles select/retain their original songs. +The original actor hooks now produce voices, shots, death screams, footsteps, +projectile effects and BJ's yell. Missing native events were restored for +player gun/knife attacks, all pickups and extra lives, wall collisions, +opening/closing/locked doors, pushwalls, elevator/invalid use, player death, +and menu movement/select/cancel. Existing actor RNG calls were preserved. +The original active non-SPEAR `TakeDamage` and `CheckWeaponChange` do not +emit standalone player-injury/weapon-selection sounds; unused identifiers +were not repurposed to invent them. + +The application's logical original mode is AdLib plus digitised sounds, +configured before loading levels even with `--no-audio`, a muted bus, corrupt +audio contents or failed SDL opening. Schabbs/Gift/Fat/Hitler die2 states +therefore use the original **140 tics**. The portable core's explicitly +non-digitised mode uses **five tics**, retained for existing silent fixtures. +Mode is never derived from device availability or volume. This intentionally +restores the original mode-dependent delay documented as absent in 6A. + +## Verification + +CART and regression commands are in [BUILD.md](BUILD.md). Automated coverage +includes synthetic, invented instruments/music/samples and owned files read +in place. It checks: + +- Archive offsets, malformed lengths/instruments/IMF, truncated files and + VSWAP sample metadata; cleanup after failed loading and read-only directories. +- Exact 700/140 Hz service, zero-delay batches, stateful loop restart, expected + full first-loop duration of each of the 27 owned tracks, 44.1/48 kHz timing, + split-buffer PCM equality, audible nonzero FM and all 87 sound identifiers. +- A deliberate channel-zero collision proving effect-before-IMF write order + on the same chip; distinct and equal-priority interruption on both lanes; + shared scream mapping and exact digitised sample duration/channel gains. +- Original positional tables/orientation, both mute/volume controls, settings + input, repeated SDL dummy lifecycle and intentional device-opening failure. +- Identical player/actor/game state and RNG after 210 gameplay tics with PCM + generation enabled versus no sound manager, at the same logical device mode. +- Both original boss delays with muted/absent hardware, all 240 map/difficulty + combinations, and all six controlled SDL weapon/finale/article flows with + actual archive loading, synthesis and dummy-device output enabled. + +The final CART Linux build and all **51** Python regression cases pass with +owned data (222 seconds). The full **ASan/UBSan** application and instrumented +C/SDL suite also passes all **51** cases (609 seconds), with +`UBSAN_OPTIONS=halt_on_error=1` and no sanitizer reports. CART's SDL3 and desktop +output-directory regression scripts pass. The Sound panel was rendered using +owned fonts and visually inspected at both volumes set to 100%; text fits. +All **35** application C translation units pass strict MinGW C11 compilation; +the Windows application also cross-links against the official SDL3 3.4.18 +MinGW SDK. A separate ignored Wine prefix runs that Windows executable through +E1M1 startup and five frames with SDL dummy video/audio. The Windows synthetic +audio executable also passes under Wine (timing, shared-chip writes, PCM, +priorities, positioning, settings and repeated dummy-device lifecycle). These +are Wine API checks, **not native Windows or Windows physical-audio verification**. +The SDK and test binaries remain in ignored `build/checks/`. + +These campaign tests are controlled encounters, not fully navigated episodes. +The reused Linux SDL static library itself is not sanitizer-instrumented. + +### Listening and physical output + +A 12-second test played original title music, pistol, guard voice, ammunition +pickup and BJ voice through SDL3, ALSA's pulse plugin, PipeWire and the physical +Intel PCH analogue stereo sink at 48 kHz. A new `s16le 2ch 48000Hz` sink input +was observed. The check was replayed on request. The user confirmed: **“I heard +it; it sounded normal.”** No audio recording or converted audio file was made. + +This establishes a short human listening check and physical Linux output, +not an exhaustive timbre/percussion/latency or DOS A/B comparison. Such a +comparison, longer device-loss/stall testing and fully navigated campaign +listening remain future verification. + +## Remaining work + +- Animated intermission counting and ENDBONUS1/2, PERCENT100 and NOBONUS + sequencing are now completed by [Milestone 6C](MILESTONE6C.md). +- Compare representative melodic/rhythm tracks and simultaneous AL effects + against DOS on the same output route. The native level calibration below + addresses the reported balance; physical DOS A/B validation remains open. +- Verify packaging, device changes and physical playback on native Windows. + PC speaker mode is optional and remains unimplemented/unexposed. + +## Native FM level follow-up — 2026-11-03 + +A user listening report found music too quiet even with saved music/effects +volumes both at 100%. Across the first 15 seconds of each owned WL6 track, +raw FM music peaks were 645–3162 in the signed 16-bit output; the title track +peaked at 1138, versus 14336 for the pistol and 24064 for a digitized voice. + +`ID_SD.c SD_Render` now applies a fixed 4× (+12.04 dB) gain to the FM bus in +its 32-bit accumulator after synthesis/interpolation and before digitized +mixing. This raises both FM music and AdLib effects; digitized samples retain +their existing levels. Slider values, saved preferences, mute/pause, shared +OPL register writes, sound priorities and 700/140/70-Hz schedules are unchanged. +The title peak is now 4552; measured pistol/voice peaks remain unchanged. +This is native output calibration, not a claim of exact DOS analogue levels. + +`tests/audio_tests.c Volume` now bounds the invented IMF tone's output level, +while `OwnedTracks` renders every complete owned loop at 100% music and rejects +clipping. All 27 tracks passed; mixed output retains the existing saturating +16-bit conversion. The six audio tests passed normally (40.079 s) and with ASan/UBSan +(195.502 s), without skips/findings. All five demo synchronization cases +passed (39.805 s), covering the four owned recordings in both renderers. +Strict C11/SDL3 and MinGW compilation passed; PR #16 records this follow-up. Private measurements/logs remain ignored in `build/`. diff --git a/docs/MILESTONE6C.md b/docs/MILESTONE6C.md new file mode 100644 index 00000000..083ea47a --- /dev/null +++ b/docs/MILESTONE6C.md @@ -0,0 +1,220 @@ +# Milestone 6C — save/load and intermissions + +Six named slots, portable native saves, transactional restoration, menu pause/ +resume and animated original intermissions are implemented. Baseline: clean tree, +CART build and all 51 existing regressions passed with owned data (235 seconds). Original +WL_MAIN.C SaveTheGame/LoadTheGame, WL_MENU.C save/load UI and WL_INTER.C +LevelCompleted/BJ_Breathe were reviewed alongside the active code and the +6/6A/6B/build reports. The requested six slots take precedence over the +archived GOODTIMES menu's ten slots. + +## State audit and checklist + +- [x] All gamestate fields: inventory, attack/weapon animation, health/lives, + keys, score/thresholds, episode/floor/difficulty, counts, level clock and + boss kill-camera coordinates. +- [x] Eight completed-floor statistics records. +- [x] Player and every allocated actor: class, coordinates, movement, health, + direction, flags, alert/reaction fields, state ID and tic counter. Projectiles + and dying bosses use the same explicit fields and state registry. +- [x] Actor pool high-water mark, free holes, original linked ordering and + exact tile reservations. Occupancy cannot be rebuilt solely from positions: + overlapping patrol destinations and actor slot reuse affect continuation. +- [x] Static objects/collected items and blocking cells; runtime wall/floor + areas, pushable markers, moving wall phase, position, coordinates/direction. +- [x] Doors including lock/type, position, action and hold timer. +- [x] RNG table index, face-count RNG timer, attack latch, chaingun face latch, + movement angle fraction, noise flag and last thrust. +- [x] Logical digitised mode, preserving original 5/140-tic boss state delays + independently of output hardware and volume. +- [x] Immutable original map restored from resource-identified game archives. +- [x] Exclude/rebuild presentation palette, ray buffers, input queues, wall + heights, PCM/OPL state and device pointers. Actor view/visibility fields + remain saved because the next attack can consume the previous frame's view. + +Saving is limited to living normal gameplay, including attacks, active +projectiles and boss death states before a victory camera begins. Death, +intermissions and victory cinematics are not save points. This removes any +need to serialize the cinematic framebuffer or live camera pointers. + +## Using saves + +Escape during living gameplay pauses the simulation and opens the original +control panel. Save Game opens six slots; arrows select, Enter edits/selects, +Backspace deletes and Escape cancels. Descriptions use the existing ASCII +keyboard/font, at most 31 characters and 121 pixels. A blank edit receives an +E#/Floor description. Replacing any existing file, including corrupt or +unsupported versions, requires Y; N/Escape preserves it. Load Game also works +from a fresh application's main menu. Errors remain inside the slot screen; +cancelling restores the paused game. Back to Game resumes it without advancing +the game clock while menus/fades were displayed. + +`SDL_GetPrefPath(NULL,"wolf3d-revive")` supplies a writable per-user directory, +normally `~/.local/share/wolf3d-revive/` on Linux (`XDG_DATA_HOME` respected) or +`%APPDATA%/wolf3d-revive/` on Windows. The six files are `slot1.w3s` through +`slot6.w3s`. Back up these files to preserve progress. No game archives or saves +are written into Steam, the source tree or `WOLFSRC/`. Failure to obtain/create +the user directory disables save/load and reports the reason. There is no +persistent configuration in this milestone. + +## Version 1 format + +Every disk integer is an explicit four-byte little-endian word; signed values +use a defined two's-complement encoding. Booleans are words 0/1. C structure +padding, pointer widths, process addresses and host endianness never enter the +file. The payload is bounded to 256 KiB before allocation. + +| Header byte | Value | +| --- | --- | +| 0 | Seven ASCII bytes `W3RSAVE`, then NUL | +| 8 | Format version, currently 1 | +| 12 | Header length, 96 bytes | +| 16 | Exact payload byte length | +| 20 | Zero-based slot identifier | +| 24 | IEEE CRC32 of the complete file, with this word zeroed | +| 28, 32, 36 | Zero-based episode, floor and difficulty | +| 40 | 32-byte NUL-terminated printable ASCII description | +| 72, 76, 80 | CRC32 identities of MAPHEAD, GAMEMAPS and VSWAP | +| 84 | Original logical digitised-device mode, 0/1 | +| 88–95 | Reserved, written zero | + +Payload order is deliberately fixed: the 28 game words, eight six-word floor +statistics records, RNG/device mode/actor high-water/static/door counts, player, +allocated actor records, statics, doors, moving-wall fields, the 64×64 grids +(x-major), noise/thrust and hidden combat/movement controls. `WL_SAVE.c`'s +`GAME_INTS`, `ACTOR_INTS` and `Payload` define each field in this order. Actor +records contain 20 data words plus state and next identifiers; pool slots also +have an allocation boolean. Grid cells contain wall, area, actor reference, +static-block and pushable words. Missing actor references are signed -1; +0–149 refer to pool indices. Player.next heads the preserved list. + +`WL_SAVE_STATES.inc` lists 303 stable state identifiers; 0 means NULL. Append +new identifiers without reordering existing ones; incompatible changes require +a format version bump. No unknown version is guessed or deserialized. Metadata +inspection reads the header and streams CRC verification without constructing a +simulation, with distinct empty/corrupt/unsupported/unavailable labels. No DOS +save import is offered, and future version migration is not implemented. +CRC32 detects damage and resource mismatches; it is not authentication. + +## Write and load transactions + +Writes capture a snapshot and validate it before creating a same-directory, +exclusive temporary file. The complete file is written, flushed, synced and +closed before replacement. POSIX overwrite uses `rename`; an unapproved new +slot uses `link` for atomic create-if-absent, preventing a concurrent writer +from being overwritten. The temporary name uses process ID and a local counter, +never gameplay RNG. Windows uses UTF-8-to-wide filesystem paths, `_commit` and +`MoveFileExW` with write-through and optional replacement. Failure removes the +temporary file and retains the previous slot. POSIX directory syncing is best +effort after commit; ultimate crash/power-loss guarantees depend on filesystem +and OS support. Unapproved creation can fail on filesystems without hard links. + +Loading stages and validates the entire snapshot before replacing the active +map: lengths, checksum, version/slot/metadata, resource identity, counts, enums, +state IDs, coordinates, door-wait indices, linked-list cycles/membership, +occupancy references, door/pushwall relationships, reachable-map enclosure, +inventory and hidden timers. +Original map decoding and sprite/wall resource validation also complete before +commit. `CA_ReadMap` and `CA_InstallMap` separate staging from the last fallible +map allocation. Pointer reconstruction and simulation installation then require +no allocation. Failure leaves the live simulation, clock, RNG and previous save +unchanged. Resource caches may warm during validation. + +Pool holes and high-water allocation are preserved, rather than respawning a +level. This matters when a projectile or morphed boss takes the next free slot. +Actor tile reservations are restored exactly, including overlapping original +patrol reservations. Previous-frame visibility/view fields remain available +for attacks on the first resumed tic. A paused redraw uses local actor copies +and does not collect pickups or activate actors. + +## Audio and intermissions + +Loading stops obsolete effects, restarts the correct level song and invalidates +queued SDL output. Current music/effects volumes and mute settings remain in +force; PCM/OPL/device state is rebuilt, never serialized. The saved logical +5/140-tic boss-delay mode is restored independently of mute, `--no-audio` or +physical output failure. Existing emu8950 synthesis is unchanged. + +`WL_INTER.c` now resumes the original counting loops at their sound waits and +30-VBL boundaries. Time counts in 500-point steps, ENDBONUS1 plays every 50 +iterations, and ratio blips every ten percentage points. ENDBONUS2 ends ordinary +counts; perfect/zero ratios wait 30 tics before PERCENT100/NOBONUS. Perfect ratios +add 10,000 points. Counters otherwise advance immediately, as in the source, +rather than acquiring an arbitrary per-frame speed. Display and sound sequencing +use 70-Hz tics and the original 140-Hz AdLib effect lengths, even with muted or +unavailable output. No audio-device queue length controls the simulation. + +BJ alternates breathing frames after the source's initial >10 then >35-tic +intervals. A key during counting shows final values and awards the bonus once; +a separate acknowledgement leaves. Natural completion awards once, records +ratios and waits for acknowledgement. Secret floors show their original 15,000 +bonus. Counting, breathing and sound events never consume gameplay RNG. Menu +fades and the existing fixed-tic presentation remain native resumable routines, +not a DOS instruction-timing emulation. + +## Verification + +Verified on 2026-11-02: + +- Final CART Linux build passes (38 application C translation units). The full + **64-case regression suite with owned data passes** (305.648 seconds), including + all 240 map/difficulty combinations and six controlled SDL finale paths. +- The final **13 save/intermission cases pass with ASan/UBSan** (55.923 seconds) + and without sanitizers (37.963 seconds), including the later enclosure and + door-wait validation. The application also builds with strict warnings as + errors and sanitizers and passes an owned E1M1 five-frame SDL smoke test. +- The full application/C/SDL ASan/UBSan run passes **63 cases** (791.936 + seconds), with `UBSAN_OPTIONS=halt_on_error=1` and no sanitizer reports. It + started before the additional six-episode continuation case was added; the + final 13-case run above includes that case and all final save-validator and + intermission changes. All 64 current cases therefore have sanitizer coverage. +- CART's SDL3 and desktop-output-directory regression scripts pass. +- All 38 C units cross-compile/link with strict MinGW C11 warnings as errors + against the official SDL3 3.4.18 MinGW SDK. The Windows SDL save/menu executable + passes write/overwrite/cancel/corrupt-slot checks and a separate-process load + under Wine, including a UTF-8 directory component. **Wine is not native Windows + verification.** The Windows application also passes five-frame startup under + Wine. A Windows-produced save loads in Linux and reserializes to an identical + complete payload. SDKs, prefix and executables stay under ignored `build/checks/`. +- Original-art six-slot selection, name editing, overwrite/load panels and + counting/final intermission captures were inspected. BJ frame changes are + separately checked at the original 11/36-tic boundaries. Captures remain + private and ignored. Linux application startup creates its SDL user-data + directory with `XDG_DATA_HOME` redirected away from the game-data directory. + +The reused SDL static library is not sanitizer-instrumented. The established +Milestone 6B physical Linux listening check remains documented in +[MILESTONE6B.md](MILESTONE6B.md); this milestone adds automated sequencing and +SDL output checks, not a new human DOS A/B listening claim. + +Tests added in `test_save.py`, `save_tests.c`, `save_sdl_tests.c` and +`intermission_tests.c` cover: + +- All six slots and explicit header/CRC layout; registry lookup for every state. +- Separate-process load and continued simulation, including six episodes with + synthetic and owned archives; complete payload/RNG comparison against an + uninterrupted run with identical inputs. +- Mid-attack inventory, health/lives/keys/score, collected items, active doors and + pushwalls, projectile movement, dead bosses, freed actor holes and respawn. +- Truncation, bad lengths/checksums/versions, wrong source identity, malformed + state/object/grid references and counts, with unchanged live-state payloads. +- Read-only directory and partial-write failure; previous slot equality, + temporary cleanup and competing create-if-absent writers. +- SDL menu events, name editing, overwrite/cancel, empty/corrupt/unsupported + slots, failed load preservation, pause/resume and UTF-8 save-directory paths. +- Current audio settings, level music, obsolete effects/queued-output generation + and logical boss delay restoration. +- Exact intermission sound ordering/waits, tempo, skip/acknowledge, single awards + and unchanged RNG, using independently generated 140-Hz test effects. + +## Limits + +Save points are restricted as described above. Music restarts at the level's +beginning after load; it does not resume at an exact sample/OPL phase. Descriptions +use the existing unshifted ASCII input mapping, without Unicode text editing. +There is no timestamp, cloud storage, DOS compatibility or generic migration +framework. Native Windows physical-device testing and exhaustive DOS A/B audio +comparison remain outstanding. Controlled campaign tests are not fully navigated +human playthroughs of all episodes. Existing licensing and attribution remain +unchanged; no commercial asset bytes or screenshots are committed. + diff --git a/docs/MILESTONE6D.md b/docs/MILESTONE6D.md new file mode 100644 index 00000000..cef3f6f7 --- /dev/null +++ b/docs/MILESTONE6D.md @@ -0,0 +1,181 @@ +# Milestone 6D — Classic and Modern controls + +Work is on `feature/6d-wasd-controls`, based on the initial GitHub WASD commit +`22a20ea`. PR #1 remains available for review; master and WOLFSRC are unchanged. + +## Audit and revision + +The initial branch added a second `ControlMovement()` call for A/D. It built, +but combined Alt+arrow and A/D could apply two strafes in one tic. Forward plus +strafe also produced diagonal acceleration and repeated collision/tile-trigger +work. There was no preset, relative mouse input or settings UI. + +Classic defaults now use the existing DOS control path, compared with +`WOLFSRC/WL_AGENT.C` and `WL_PLAY.C`: the original turn-angle fraction, 35/70 +keyboard rate, 150 forward/strafe and 100 backward movement scales, collision +sliding and original Alt+forward diagonal behaviour remain. Modern combines +translation before one collision move and one tile-interaction update per tic. +Each action is boolean across its alternative bindings, opposite directions +cancel and combined strafe sources are clamped to one direction. + +Modern diagonals preserve the forward/backward/strafe speed ratio, with their +vector length limited to the larger single-axis speed. Integer rounding may +shorten a diagonal by a few map-coordinate units (less than 0.01% of a tile). +`thrustspeed` uses that bounded speed, so walking diagonally does not accidentally +acquire the enemy hit-chance behaviour of running. Classic's original diagonal +behaviour is deliberately retained. If dedicated strafe keys are assigned in +Classic, they use the combined translation path while active. + +Both presets still run the same player, combat, actor, collision and map logic +at 70 Hz. Input collection never draws from gameplay RNG or changes the clock. + +## Default mappings + +Classic is the initial preset, preserving existing behaviour. Settings last for +the current application session, across new games and loads. No configuration +file or new serialization format is introduced. + +| Action | Classic | Modern | +| --- | --- | --- | +| Forward / backward | Up / Down (keypad 8 / 2) | W / S, with Up / Down alternatives | +| Turn left / right | Left / Right (keypad 4 / 6) | Mouse X, Left / Right (keypad 4 / 6) | +| Strafe left / right | Alt + Left / Right | A / D; Alt + arrows also work | +| Run | Either Shift | Either Shift | +| Fire | Either Ctrl | Left mouse button or either Ctrl | +| Use/open | Space | Right mouse button or Space | +| Weapons | 1–4 | 1–4 | +| Menu/pause | Escape | Escape | +| Mouse | Disabled initially | Enabled initially | + +Mouse can also be enabled in Classic. There is no vertical mouse movement, +freelook, acceleration curve or aim smoothing. The original slower backward +speed and original Shift-running speeds remain. + +## Bindings and menus + +Control in the main menu opens preset, mouse enable, sensitivity, invert-X, +reset and binding settings, using the existing fonts, colours and 320×200 +renderer. Up/Down selects a row; Left/Right or Enter changes a value. Switching +presets resets bindings and mouse options to that preset's defaults. Reset +Defaults restores the currently selected preset. + +The key-binding page has two alternatives for each action, including turning, +dedicated strafing, run, Alt-strafe, fire, use, weapons and pause. Up/Down browses +all actions, automatically paging five rows at a time. Left/Right chooses the +alternative. Enter waits for a key, Delete clears that slot and Escape cancels +capture or returns to the preceding page. Conflicts leave the old binding intact +and ask for another key; no existing action is silently unbound. Escape remains +a global pause/cancel fallback even when the configurable Menu binding changes. +Mouse buttons have fixed left-fire/right-use assignments when enabled. + +`WL_CONTROLS.c/.h` holds the small action-to-two-keys table and pending input. +Physical key identifiers match SDL3 USB scancodes; the gameplay core does not +include SDL headers. Letters in the UI label physical QWERTY positions, rather +than translated Unicode characters. This works independently of Linux/Windows +keyboard layout; users can bind their preferred physical positions. Menu +navigation and save-description typing retain their existing ID_IN mapping. +There is no text-entry/layout rewrite in this milestone. + +SDL key events feed physical gameplay keys and the separate, original menu +scan state. Legacy set-1 engine/test input calls are translated at that boundary. +This preserves keypad/modifier alias behaviour in menus while allowing separate +left/right modifier assignments for gameplay. Rapid make/break input survives +until one simulation tic consumes it. Transitions clear pending input so held +menu keys/buttons cannot start movement or fire on resume. + +## Mouse timing and capture + +`sdl_input.c` uses `SDL_SetWindowRelativeMouseMode`, with no OS-specific input +API. Capture is enabled only for living gameplay with mouse enabled, after +fade-in. Menus, intermissions, death/victory presentation, focus loss and shutdown +release it. Resume/respawn/focus regain restore it when appropriate. Capture +transitions discard old mouse motion; mouse buttons held across menus require +release and a fresh press. Keys received while unfocused are ignored. The game +continues its existing simulation while unfocused; focus loss does not add an +automatic pause rule. + +Sensitivity ranges from 1 to 40, default 10. Each relative horizontal count adds +`sensitivity / 20` degrees: the default is 0.5 degrees/count. Invert X reverses +its sign. Fractional event counts accumulate, and whole twentieth-degree units +enter the existing angle-fraction accumulator on the next 70-Hz tic. Rendering +frames never rotate the player directly. Pending motion is consumed once, not +repeated across catch-up tics. Non-finite events are ignored; unusually large +events and pending rotation are bounded to prevent overflow. + +Relative-mode failure logs a clear error and leaves keyboard controls usable. +It is retried after a focus/capture lifecycle change, rather than logging on +every presentation frame. SDL remains responsible for the actual platform +capture and relative-event implementation. + +## Saves and scope + +Save version 1 and audio formats are unchanged. The existing saved angle fraction +also preserves fractional mouse turning already applied to the simulation. +Pending keys/clicks/motion are transient input and are cleared by loading. +Current control settings stay in force after load, just as current audio +volumes do; they are not restored from the save file. Tests compare complete +save payloads after equivalent Classic/Modern forward input and after continuing +a Modern save with identical new input. + +No audio synthesis, assets, fullscreen/widescreen, alternative artwork, external +input framework or original WOLFSRC file was changed. + +## Verification + +Verified on 2026-11-02: + +- CART Linux build passes; all 40 application C translation units also compile + with strict C11 warnings as errors in the sanitizer and MinGW builds. +- Full **67-case regression suite with owned WL6 data passes** (364.220 seconds), + including all 240 map/difficulty combinations and all six controlled finale + paths, audio loops, menus and saves. +- Full **67-case ASan/UBSan suite passes** (842.379 seconds), with + `UBSAN_OPTIONS=halt_on_error=1` and no sanitizer reports. The final additional + controls checks also pass separately under sanitizers (17.607 seconds). +- CART's SDL3 and desktop-output-directory regression scripts pass. +- The application and controls harness cross-link against the official SDL3 + 3.4.18 MinGW SDK. Under an isolated Wine prefix, the controls harness passes + Classic/Modern movement, settings, conflicts, mouse capture/buttons, focus, + pause/resume and save continuation. Its complete Windows save payloads match + for equivalent Classic/Modern input and uninterrupted/restored Modern input. + Windows application startup also passes five frames with dummy drivers. + These are **Wine API tests, not native Windows physical-input verification**. +- Final sanitizer application startup passes an owned E1M1 five-frame smoke + test with SDL dummy video/audio. Controls tests use both independently + generated synthetic archives and original owned files, without modifying + the game-data directory. + +The new controls harness covers: + +- Classic forward/back/turn/keypad/Alt/run behaviour and Modern WASD translation. +- Opposite directions, duplicate alternatives, Alt plus dedicated strafe, + bounded diagonal/run speeds, thrust-speed classification and static collision. +- Mouse count accumulation, sensitivity/inversion, disabled mouse, quick clicks, + edge-triggered use, large/non-finite motion and valid angle wrapping. +- Conflicting/invalid bindings, reset/preset switching, weapon rebinding, custom + pause keys and independent global menu navigation. +- Original-enemy/RNG and full-save-payload equality for equivalent forward input + in both presets; unchanged RNG during event accumulation; deterministic Modern + save/load and retention of current controls when loading a different preset. +- SDL event-driven settings/binding pages, conflict feedback, relative-mode + enable/release, focus loss/regain, ignored unfocused keys, held menu buttons, + pause-clock preservation and clean shutdown. + +Original-art controls and binding panels were captured and visually inspected; +private captures and SDK/test binaries stay in ignored `build/checks/`. + +The pre-existing SDL gameplay test was corrected to emit focus-regain events +before expecting new keyboard input. Its former sequence intentionally sent +keys while unfocused, which the new input boundary correctly ignores. + +## Remaining verification gaps + +Session-only settings reset when the application exits. No TOML persistence, +Unicode key-name rendering, mouse-button rebinding or gamepad support is added. +Native Windows physical keyboard/mouse testing remains required; MinGW and Wine +checks do not establish that. SDL's reused static library is not sanitizer +instrumented. Exhaustive multi-monitor, unusual mouse hardware and all keyboard +layouts are not claimed. Existing campaign coverage uses controlled encounters, +not full human playthroughs. A hands-on Linux test has been offered in the open +desktop window. The user volunteered to test; hands-on feedback is still pending +at the time of this report. No successful human-input test is claimed. diff --git a/docs/MILESTONE6E.md b/docs/MILESTONE6E.md new file mode 100644 index 00000000..3257869b --- /dev/null +++ b/docs/MILESTONE6E.md @@ -0,0 +1,183 @@ +# Milestone 6E — Native SDL3 display + +Work is on `feature/6e-native-display`, completing the initial `dc803ae` +implementation in PR #2. The branch was fetched and checked out from a clean +working tree, and reviewed against current `origin/master` (`51d767d`, merged +Milestone 6D). Local master, WOLFSRC, commercial assets and save formats are +unchanged. PR #2 remains open for review and is not merged. + +## Review and fullscreen implementation + +The initial change added a 320×240 logical presentation and two shortcuts. It +used an optimistic fullscreen boolean, logged synchronous failures but did not +reconcile asynchronous window-manager transitions, and forwarded shortcut +releases and the chord's Alt press into the input path. SDL integer presentation +also crops windows smaller than its logical size unless the application +supplies a fallback. + +`sdl_video.c` now queries `SDL_GetWindowFlags()` for actual fullscreen state. +`SDL_SetWindowFullscreenMode(window, NULL)` selects borderless desktop +fullscreen before `SDL_SetWindowFullscreen()`. No exclusive display mode or +desktop resolution change is requested. Only an outstanding request has a +target state; that target is never reported as the actual state. + +Window requests are asynchronous. Polling/presentation reconciles SDL flags +and observed window dimensions without blocking the simulation in +`SDL_SyncWindow()`. A three-second deadline reports rejected/constrained +requests and clears pending state. A later external/window-manager change is +still reflected by the next status query. Synchronous failures preserve the +previous scaling preference and remembered size, log SDL's error and show an +error in the settings panel. A successful change clears the error. + +The last ordinary windowed size is remembered in window points. Fullscreen, +maximized and minimized dimensions do not overwrite it. Leaving fullscreen +restores that size; choosing a size while fullscreen changes the remembered +size for the next windowed transition. Manual resizing is supported, including +non-4:3 windows. No persistent configuration file is introduced. + +## Aspect ratio and scaling + +The original VGA setup in `WOLFSRC/ID_VL.C` starts with BIOS mode 13h and +configures planar VGA access. Its 320×200 game image was intended for a 4:3 +display, with pixels taller than square pixels. Displaying those samples as a +square-pixel 320×200 image would instead produce 8:5 proportions. + +The existing framebuffer and texture remain **320×200**. The nearest-filtered +texture fills a **320×240** SDL logical canvas: a vertical factor of 240/200, +or 6/5. This corrects presentation without changing drawing coordinates, +raycasting, artwork, view size or gameplay. Comparison here is against the +original VGA setup and expected display geometry, not a physical DOS/CRT +side-by-side test. + +For drawable output dimensions `W × H`, fit scale is +`s = min(W / 320, H / 240)`. SDL centers the resulting `320s × 240s` viewport, +with at most pixel rounding at its edges. Integer mode uses `floor(s)` when +`s >= 1`, leaving black borders around whole multiples of the corrected +canvas. Integer scaling refers to that canvas: the 6/5 correction means raw +source rows do not necessarily have equal integer heights. At a canvas scale +divisible by five, source rows have equal whole-pixel heights. + +If either drawable dimension is below 320×240, integer mode temporarily uses +fit scaling instead of SDL's minimum 1× integer viewport, which would crop. +For outputs below 4×3 pixels, presentation clears to black rather than drawing +an unusable zero-size rounded viewport. The renderer clears the entire target +black before drawing; wide and tall windows both retain 4:3 content. Texture +uploads still occur only when framebuffer or palette content changes. + +## Settings and shortcuts + +The former disabled Change View row is now **Display**, using the original +fonts, colours, panel drawing and menu transitions in the 320×200 framebuffer. +It is available at the main menu and while gameplay is paused: + +| Setting | Behaviour | +| --- | --- | +| Fullscreen | Toggle borderless desktop fullscreen/windowed | +| Integer scaling | Toggle integer canvas scaling/fit | +| Window size | Select 1×–5×: 320×240 through 1600×1200 window points | +| Reset defaults | Windowed, fit, 3× (960×720) | + +Up/Down selects; Left/Right or Enter changes a value. Reset requires Enter. +Escape returns to the preceding menu. A custom resize shows its dimensions; +arrows return to the preset range. Pending changes show “Switching...”, and +the panel reports failures and the small-window fit fallback. Settings apply +for the current session and survive game loads; they are not serialized. + +Alt+Enter, including keypad Enter and either Alt key, toggles fullscreen. +F11 toggles integer scaling and is reserved from gameplay bindings. Shortcut +down, repeat and matching release events are consumed before menu/game input. +Only the Alt keys actually participating in a chord are suppressed; the other +Alt remains usable. Focus loss clears shortcut suppression. Unfocused +shortcuts are ignored. Fullscreen requests discard stale keyboard/button-edge +input so Enter cannot select a menu item or trigger an assigned action. +Held keyboard controls need a fresh press after such a transition. + +## Capture, DPI and gameplay boundary + +The window uses `SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY`. +Window presets/restoration use `SDL_GetWindowSize()` points. Scaling decisions +use `SDL_GetRenderOutputSize()` drawable pixels, rather than logical output +dimensions or window points. SDL owns the centered viewport and recomputes it +as the drawable changes. No extra renderer or graphics API is introduced. + +Relative mouse mode releases while a display request is pending. It returns +only for focused living gameplay with mouse enabled; menus, focus loss and +pause retain the existing release rules. Old relative motion and input edges +are discarded across transitions. Held mouse buttons require release before +they can fire/use again, preserving Milestone 6D's protection. + +Display state is outside the simulation and save payload. The small menu +backend has two get/set callbacks, so headless gameplay does not depend on +SDL video. Display operations do not call game RNG, advance simulation tics, +change the original 70-Hz clock, alter actors or rescale raycasting inputs. +Sound scheduling and save version 1 remain unchanged. + +## Verification + +Tests use independently generated archives and the player's installed original +WL6 data read-only. No game data, screenshots, SDKs or binaries are committed. +The new `tests/display_tests.c` / `tests/test_display.py` cover: + +- Fullscreen entry/exit, external SDL state changes, custom window-size + restoration, preset selection while fullscreen and reset defaults. +- Integer/fit viewport calculations and actual pixel readback of black bars + and image colours in wide/tall windows, from 1×1 to 1920×1080. +- Drawable/window-pixel dimension agreement, high-density window flag and no + redundant framebuffer uploads during presentation-only changes. +- Shortcut repeats/releases, keypad/right-Alt chords, opposite-Alt usability, + F11 binding rejection and ignored unfocused shortcuts. +- Injected fullscreen, presentation and size failures, denied asynchronous + requests, timeout recovery and subsequent successful changes. Fault hooks + exist only in builds defining `WOLF3D_DISPLAY_TEST`. +- Original-art menu navigation, paused display changes, focus/capture + release/regain, resume, unchanged RNG/tics during display calls and complete + save-payload equality after equivalent gameplay with/without display changes. + +Linux dummy video does not implement minimize; that optional test checks +restore only when minimize is supported. It does not pretend the operation +succeeded on an unsupported driver. + +The full **70-case normal regression suite with owned WL6 data passes** +(314.104 seconds). This includes all 240 original map/difficulty combinations, +all six controlled finale paths, existing controls/audio tests and save/load +regressions. The full **70-case ASan/UBSan suite also passes** (756.221 seconds), +with `UBSAN_OPTIONS=halt_on_error=1` and no sanitizer reports. Application and +test C builds use `-std=c11 -Wall -Wextra -Wpedantic -Wconversion -Wshadow +-Werror`; sanitizer builds additionally use address/undefined sanitizers and +frame pointers. Commands and SDK setup are in [BUILD.md](BUILD.md). + +Additional completed checks on 2026-11-02: + +- CART Linux build and CART SDL3/desktop-output-directory regressions pass. +- The final three focused display tests pass under ASan/UBSan with owned data + (20.328 seconds), including the explicit repeat-event check. +- All 41 application C units and the display harness cross-link with strict + C11 warnings as errors using MinGW and the official SDL3 3.4.18 SDK. + Windows geometry and synthetic gameplay/display tests pass under Wine with + dummy video/software/audio drivers. Complete save payloads match after + continuous gameplay versus equivalent gameplay with display changes. + A five-frame owned-data Windows application smoke also passes under Wine. +- A separate Linux X11 desktop smoke check passes actual asynchronous + fullscreen entry at 1920×1200, integer scaling, restoration to 960×720, + resize to 1000×600 and mouse capture before/after transitions. It uses the + application's SDL display API and normal event/presentation path, without + blocking synchronization in that path, then closes itself. +- The owned-data Display panel was captured and visually inspected. The + original fonts fit all four settings and help text without overlapping. + Captures remain private in ignored `build/checks/`. +- Normal and ASan/UBSan Linux application startup pass five owned E1M1 frames + with dummy video/audio and isolated user-data directories. + +## Known limits + +Physical high-DPI/2× monitors, multi-monitor moves, unusual desktop window +managers and native Windows hardware have not been tested. Dummy and the +available Linux desktop both exposed 1× pixel density; tests validate drawable +calculations and the high-density flag, not a real Retina/2× transition. +MinGW/Wine checks establish API/build coverage, not physical Windows behaviour. +The desktop smoke is automated and does not establish a human keyboard/mouse +test or DOS visual equivalence. The reused SDL static archive is not sanitizer +instrumented. Campaign regressions cover all maps/difficulties and controlled +finale paths; full human playthroughs are not claimed. Settings are session-only. +There is no widescreen gameplay, content filter, new artwork, renderer or GUI +framework in this milestone. diff --git a/docs/MILESTONE6F.md b/docs/MILESTONE6F.md new file mode 100644 index 00000000..6d8ef2f8 --- /dev/null +++ b/docs/MILESTONE6F.md @@ -0,0 +1,247 @@ +# Milestone 6F — Persistent TOML preferences + +Work is on `feature/persistent-toml-settings`, PR #6, starting from `4f75fc7`. +The initial implementation built with CART and passed the existing **78-case +owned-data suite** (289.035 seconds), but had no configuration-specific tests. +Review found truncating/unreported writes, permissive partial parsing, duplicate +keys, binding-key suffix acceptance, order-dependent binding conflicts, wrong +mouse defaults for preset-only files, lost custom window dimensions and an +uninitialized path pointer on failed video startup. These are corrected here. + +No WOLFSRC, commercial archives, game/save formats, 320×200 drawing, raycasting, +AI, RNG or 70-Hz simulation rules are changed. Configuration is a separate file +from the six saved games. Master is unchanged and PR #6 is not merged. + +## Location and lifecycle + +The application calls `SDL_GetPrefPath(NULL, "wolf3d-revive")` after successful +video startup and keeps that allocated UTF-8 path until shutdown. Defaults are: + +- Linux: `~/.local/share/wolf3d-revive/config.toml`; `XDG_DATA_HOME` overrides the + data root, giving `$XDG_DATA_HOME/wolf3d-revive/config.toml`. +- Windows: `%APPDATA%\wolf3d-revive\config.toml`. + +The path is never derived from `--data`, the working directory, or a commercial +archive name. Loading/writing uses UTF-8-aware Windows file APIs through the +existing save-file boundary. Preferences and `slot1.w3s`–`slot6.w3s` share the +user-owned directory but have independent content, versions and lifecycles. + +Load occurs after the audio/video backends are initialized and before the +UI/game starts. A missing file uses defaults. Normal exit, including closing +the window and finite `--frames` runs, saves current preferences. Asset/UI/ +level check-only commands do not load or write preferences. Failed startup or +abnormal exit does not save. A failed preference write reports an error while +allowing the already completed game session to exit normally. + +Malformed, unreadable and unsupported-version files leave startup defaults in +place and are **not automatically replaced on exit**. Repair or rename that +file to re-enable persistence. Semantically unsupported individual values use +defaults, with a diagnostic; other valid values still load. No original archive +is rewritten. Atomic replacement does not follow a destination symlink into +another file, including an asset. + +## Schema and defaults + +The writer emits schema version 1. An omitted version is accepted for migration +from the initial PR. The following is a valid example with all ordinary fields; +the binding keys described below are emitted for both profiles as well: + +```toml +schema_version = 1 + +[controls] +preset = "classic" + +[classic_controls] +mouse_enabled = false +invert_mouse_x = false +mouse_sensitivity = 10 + +[modern_controls] +mouse_enabled = true +invert_mouse_x = false +mouse_sensitivity = 10 + +[audio] +music_volume = 70 +effects_volume = 85 +music_enabled = true +effects_enabled = true + +[display] +fullscreen = false +integer_scaling = false +window_width = 960 +window_height = 720 + +[classic] +view_size = 15 +``` + +| Field | Accepted values / meaning | +| --- | --- | +| `controls.preset` | `"classic"` or `"modern"` | +| Profile `mouse_enabled`, `invert_mouse_x` | TOML booleans | +| Profile `mouse_sensitivity` | Integer 1–40; default 10 | +| Profile `bind_A_S` | SDL physical/USB scancode; A is action 0–14, S is slot 0/1; zero unbinds | +| Audio volumes | Integers 0–100, independently applied | +| Audio enable states | Booleans, independent of volumes | +| `display.fullscreen` | Borderless desktop fullscreen / windowed | +| `display.integer_scaling` | Integer canvas scaling / fit; tiny-window fallback still applies | +| `display.window_width`, `window_height` | Integers 1–16384, in window points; remembered windowed size | +| `classic.view_size` | Integer 4–19, independent of window dimensions | + +All 30 bindings are written in **each** profile table. Action identifiers and +default pairs are: + +| A | Action | Classic pair | Modern pair | +| --- | --- | --- | --- | +| 0 | Forward | 82, 96 | 26, 82 | +| 1 | Backward | 81, 90 | 22, 81 | +| 2 | Turn left | 80, 92 | 80, 92 | +| 3 | Turn right | 79, 94 | 79, 94 | +| 4 | Strafe left | 0, 0 | 4, 0 | +| 5 | Strafe right | 0, 0 | 7, 0 | +| 6 | Run | 225, 229 | 225, 229 | +| 7 | Alt strafe | 226, 230 | 226, 230 | +| 8 | Fire | 224, 228 | 224, 228 | +| 9 | Use/open | 44, 0 | 44, 0 | +| 10–13 | Weapons 1–4 | 30/31/32/33, 0 respectively | Same | +| 14 | Menu | 41, 0 | 41, 0 | + +For example, `bind_0_0 = 8` assigns E to primary Forward. These are physical +SDL scancodes, not ASCII, DOS scan codes or Windows virtual-key codes. Escape +is reserved for Menu; F1–F11 are reserved globally. Unknown SDL scancodes and +duplicate nonzero assignments, including repeated alternatives, are invalid. +Fixed mouse-button assignments remain left-fire/right-use when mouse is enabled. + +Each preset now owns its bindings, mouse enable, sensitivity and inversion. +Changing presets retains both profiles. Reset Defaults explicitly resets only +the selected preset. Loading validates the complete candidate binding table +before installing it, so swaps work independently of file/key order. If any +binding in a profile is invalid or conflicting, **that profile's entire binding +table falls back to its preset defaults**; its valid mouse options and the +other profile remain available. Invalid profiles are never partially unbound. + +Legacy `[controls]` mouse/binding fields are accepted as overrides for the +selected profile, after the new profile tables. Legacy `display.window_scale` +(1–5) supplies dimensions when explicit width/height fields are absent. The +writer migrates to the canonical two-profile / explicit-dimensions schema. +Loading a saved game retains the current preferences; they are not serialized +into or restored from the game save. + +## Parser policy and safety + +This is deliberately a **fixed-schema TOML subset**, not a general TOML engine. +Supported syntax includes bare keys and single-level bare table names, spaces/ +tabs, LF/CRLF, comments (including after table headers), single-line basic and +literal strings, basic-string escapes/Unicode escapes, booleans and signed +64-bit integers. Decimal signs, separators and unsigned hexadecimal/octal/binary +forms are checked without integer overflow. The emitted file also parses with +Python's independent `tomllib` implementation. + +Dotted/quoted keys and tables, arrays, inline tables, multiline strings, floats +and dates are outside this subset. Such files are rejected transactionally and +preserved, rather than being partially interpreted. Raw tabs inside strings, +escaped NUL and strings longer than 63 decoded UTF-8 bytes are also unsupported. + +The parser bounds input at 64 KiB, lines at 1024 bytes, names at 63 bytes, +records at 256 and explicit tables at 64. Embedded NUL, invalid UTF-8, truncated +escapes, invalid separators/leading zeros, integer overflow, duplicate keys +(including unknown keys), repeated tables and scalar/table collisions are +rejected. Unknown tables/keys containing supported scalar syntax are ignored. +Canonical output replaces comments, ordering and ignored fields; it does not +preserve arbitrary editor formatting or future unknown data. A declared future +schema is preserved and never migrated automatically. + +Parsing completes before any preference changes are applied. Syntactically +invalid/read-error files cannot apply a valid-looking prefix. Partial valid +files are interpreted from preset-aware defaults, not leftover state from a +previous load. Unsupported typed/range values report a warning. Diagnostics +name the key or line rather than echoing arbitrary file contents. + +## Atomic output and platform behaviour + +The serializer builds bounded output in memory, checking every formatting +operation. It then uses the existing `SaveFile_WriteAtomic` primitive: + +1. Create a unique same-directory temporary file with exclusive creation + (0600 on POSIX; user-readable/writable on Windows). +2. Check the complete write, `fflush`, file `fsync` / Windows `_commit` and close. +3. Replace with POSIX `rename` or UTF-16 `MoveFileExW` with replacement and + write-through flags. Remove temporary files on failure. +4. Attempt parent-directory sync on POSIX after replacement. + +Failure before replacement retains the previous destination byte-for-byte. +Directory synchronization is best effort where supported; universal power-loss +or remote-filesystem durability is not claimed. Concurrent writers each publish +a complete file; the last successful replacement wins. There is no per-field +multi-instance merge or locking protocol. Save-game serialization is unchanged. +Fault injection exists only in test builds defining `WOLF3D_CONFIG_TEST`. + +Display persistence distinguishes observed SDL flags from an accepted pending +request. A quick exit while fullscreen is still being applied saves the accepted +target, not a transient old window flag. Once SDL reports rejection or the +existing request timeout expires, the observed state is saved. Loading preserves +the remembered custom windowed dimensions even while fullscreen. Leaving +fullscreen after restart restores those dimensions. No blocking fullscreen +synchronization or new simulation work is introduced into normal startup. + +The GOODTIMES boss key temporarily mutes music. Shutdown restores its saved user +settings before capturing preferences, so closing the window on the C> screen +does not turn that temporary mute into a permanent preference. + +## Verification + +Verified on 2026-11-02: + +- CART Linux C11 build passes; all **44 application C translation units** also + compile with strict warnings as errors in Linux sanitizer and MinGW builds. +- Final **104-case normal suite with owned WL6 data passes** (329.054 seconds), + including all existing campaign, gameplay, audio, display and save regressions. +- ASan/UBSan passes the full **101-case run** (763.881 seconds), plus the three + subsequently added path/concurrency cases (8.725 seconds). Together these + exercise all 104 final cases under sanitizers. The final **26-case configuration + suite** also passes separately (12.261 seconds), including the final tiny- + window and exit-fullscreen size-restoration assertions. No sanitizer reports; + `UBSAN_OPTIONS=halt_on_error=1` is enabled. +- CART's SDL3 and desktop-output-directory regression scripts pass. +- Native Linux X11/software-renderer tests pass three shutdown/startup cycles + with fullscreen restored and complete canonical-file equality. Leaving + fullscreen after restart restores the custom 1000×600 window size. +- MinGW/SDL3 3.4.18 cross-builds pass. Wine/dummy-driver checks pass canonical + round trips, all six atomic-write fault stages, profile switching/reset, + fullscreen rejection/timeout and restored window dimensions, UTF-8 Unicode + directories, SDL preference paths, and synthetic/owned game/save independence. + The Windows application itself passes three restart cycles preserving every + seeded setting, and retains a future-version file unchanged. SDL's observed + Wine path is `C:\users\rgibbon\AppData\Roaming\wolf3d-revive\config.toml`. +- Full save payloads match before/after configuration I/O with synthetic and + owned data on Linux and under Wine; game time and RNG remain unchanged. + +The configuration suite builds strict C11 with warnings as errors and optionally +ASan/UBSan. Its independent TOML oracle uses Python 3.11+ standard `tomllib`: + +```sh +./build/tools/cart build --profile cart-sdl +WOLF3D_DATA=/absolute/path/to/owned/WL6 \ + python3 -m unittest discover -s tests -v +# Full sanitizer build/run commands are in BUILD.md. +``` + +The 26 focused tests cover missing/partial/legacy files, every preference, +both profiles, binding swaps/conflicts/reserved keys, malformed/duplicate/ +overflow/UTF-8 input, parser limits, 1000 deterministic corruption samples, +atomic create/partial-write/flush/sync/close/replace failures, concurrent writers, +read-only/unreadable paths, symlink safety, Unicode directories, SDL preference +paths, pending/failed fullscreen, custom/tiny window dimensions, full save-payload +and RNG/time equality, boss-key mute restoration and actual application restarts +against read-only synthetic game data. Commercial tests read the player's owned +WL6 files without copying their content into test fixtures. + +Native Linux X11 fullscreens and restarts are tested separately from dummy +video. Windows API checks use MinGW, the official SDL3 3.4.18 SDK and an isolated +Wine prefix. **Physical Windows, high-DPI/multi-monitor transitions and OS/crash/ +power-loss durability are not verified.** Reused SDL's static archive is not +sanitizer-instrumented. Existing Classic demo synchronization and other fidelity +limits remain in [CLASSIC_FIDELITY_AUDIT.md](CLASSIC_FIDELITY_AUDIT.md). diff --git a/docs/MILESTONE6G.md b/docs/MILESTONE6G.md new file mode 100644 index 00000000..bb4c114a --- /dev/null +++ b/docs/MILESTONE6G.md @@ -0,0 +1,213 @@ +# Milestone 6G: original DOS demo synchronization + +All four recordings in the tested retail WL6 data now match the instrumented +original DOS executable for every command frame at Classic view size 15, with +DOS sound disabled. Their durations are 2,764, 7,596, 4,560 and 6,624 original +70 Hz tics. This is a measured comparison, not just a survival/duration check. + +## Reference and investigation + +The initial `Demo_Progress()` implementation compiled with CART before gameplay +changes. Eight Classic regression cases passed, including added assertions for +map, total/consumed commands, raw button bits, null/inactive queries, read-only +RNG behavior and stopped playback. The initial owned recordings died after +1,048, 928, 1,532 and 396 tics respectively. + +The reference is the historical `WOLFSRC/WOLF3D.EXE` supplied with this repository, +paired with `WOLFSRC/WOLF3D.MAP`. These files have SHA-256 identities: + +- EXE: `8614a3e4623b66181bf0aa88fc5a4ca36cb97fe5ef8c3b903954dfaaf683ab9b` +- MAP: `b3058257601f156fee914dcc926b5857753326ac0f1eada65bb0856a7b3f1928` + +`scripts/demo_reference.py` assembles a small 16-bit logger with GNU binutils +and builds an instrumented **copy** of that DOS executable in a private output +directory. It checks both identities before applying address-based hooks, +rebuilds the MZ relocation table, and leaves tracked `WOLFSRC` untouched. It +replaces the attract-menu loop with calls to the original `PlayDemo(0..3)` and +skips startup acknowledgement. A wrapper calls the original `UpdateSoundLoc` +and then records the completed frame, preserving registers, flags and segments. +Player/actor thinkers, weapon logic, map loading, collision, renderer, RNG and +recorded commands in the DOS executable are not replaced. + +This is executable instrumentation, **not a fresh compilation of the Borland C +engine**. A temporary source copy was tried with installed Open Watcom 2.0; +compilation stopped at missing Borland headers and `_seg` pointer extensions. +The original binary plus its matching symbols provides the actual DOS reference +without substituting the native port's code or changing historical source. +DOSBox 0.74-3 executed it. No physical DOS computer was used. + +The runner copies only the eight required original archives into its private +working directory and creates a private DOS configuration: view size 15, +sound/music/digitized modes off. It does not copy the player's saves or settings. +The normal reference run retains the original four-tic real-time wait. Optional +`--fast` skips only that wait, retaining the original `TimeCount` assignments and +`tics=DEMOTICS`. Every existing record byte of the 5,386-frame timed trace was +compared with the accelerated trace and matched. The final runner adds the door +count to each record. Neither runner is linked into ordinary gameplay. + +## First divergences and corrections + +The first full-trace difference on the initial branch is visibility at command +1 in **each** recording: the port explicitly marked the player's starting cell +visible; the DOS raycaster only marks cells crossed by rays. This can affect +pickups. Actor projection also used `width/2` rather than DOS `width/2-1`. + +The first projected actor difference and first player/inventory/RNG difference +were located independently for each initial recording (command numbers are +one-based, four original tics per command): + +| Demo / source map | First actor projection difference | First primary-state difference | Native vs DOS | +| --- | ---: | ---: | --- | +| 0 / 37 (E4M8) | 51 / tic 204 | 33 / tic 132 | ammunition 88 vs 80 | +| 1 / 43 (E5M4) | 135 / tic 540 | 190 / tic 760 | ammunition 2 vs 1 | +| 2 / 56 (E6M7) | 12 / tic 48 | 167 / tic 668 | ammunition 23 vs 22 | +| 3 / 31 (E4M2) | 20 / tic 80 | 72 / tic 288 | ammunition 5 vs 4; RNG index 156 vs 157 | + +After correcting each cause, tracing continued from the first newly differing +frame. The resulting shared gameplay corrections follow the original sources: + +- `WL_DRAW.C` / `WL_DR_A.ASM`: remove the artificial starting-cell visibility; + restore `centerx` for actor/tile projection, rotation and weapon targeting; + preserve `FL_VISABLE` when projection is too close or a state has no shape. + DOS clears that flag only on the non-visible branch. +- `WL_AGENT.C T_Attack` / `WL_PLAY.C PollControls`: a fresh attack press during + an attack clears the current button state. That cleared state becomes the + next frame's held state, including the attack's ending frame. Keep raw + recorded bits separate from this latch. Use actions are suppressed during + attacks with the same held-state semantics. This fixes subsequent shots + without changing weapon tables, ammunition grants or demo commands. +- `WL_STATE.C KillActor`: clear the actual death cell after setting `tilex/y` + from position. DOS can retain an old destination reservation; purging every + reference to the dead actor changed door and movement behavior. +- `WL_ACT1.C`: door obstruction uses the marked grid, including corpses, and + original center-row/column tests. Opening fully releases the reservation in + the doorway. Closing checks its occupied cell rather than an enlarged + physical bounding square. Continue the original blocked-door timer instead + of clamping at 300, with explicit signed-16-bit wrap semantics. +- `WL_AGENT.C TryMove` and `WL_STATE.C TryWalk` (native `WL_OBJECT.c`): honor + grid occupancy rather than testing every physical actor or independently + re-blocking a door whose integer marker has been replaced by an actor. + For demo 3 the remaining movement divergence was command 734, tic 2936: + the native Y position stayed at 3,637,211 while DOS reached 3,664,601. The + DOS doorway contained an actor reservation rather than a solid integer tag. + +The RNG table/index algorithm, recorded bytes, movement constants, ray traversal, +weapon tables, 320×200 framebuffer and normal one-tic/70 Hz stepping are unchanged. +No immunity, extra ammunition, synthetic movement or per-map/demo workaround was +introduced. Save version/layout remain version 1; validation now accepts the +legitimate 16-bit door timer range instead of rejecting blocked timers over 300. + +## Trace schema and repeatable comparison + +`tests/demo_trace.c` is a developer harness, separate from the application. It +queries `Demo_Progress()` and advances exactly one four-tic command per step. +It emits a starting snapshot and then one snapshot after each completed frame: + +- `F`: demo, consumed command count, original tic clock, player X/Y/angle, + health, ammunition, RNG index, raw buttons and signed recorded X/Y commands, + weapon, attack frame and attack countdown. +- `A`: actor order, stable state **name**, position/angle, destination tile, + class, tic count, hit points, direction, speed/distance, temporary state, + flags, activity and projected position/height. The number of rows is the + actor count; no process addresses enter the portable trace. +- `V`, `M`, `Q`, `D`: visibility, runtime tiles, actor reservation slots and + door orientation/lock/action/timer/position. + +The DOS logger captures the corresponding original structures, current command +bytes and RNG index; `tests/demo_trace_tools.py` decodes explicit little-endian +16/32-bit fields and resolves state pointers using the original MAP. Bounds and +actor-list cycles are checked. It streams records rather than retaining a whole +trace in memory. Comparisons use completed frames, not the optional native +starting snapshot. + +Only unused DOS door timers are normalized: `SpawnDoor` does not initialize the +field, and `DoorOpening` resets it before `dr_open` can use it. Timers **are** +compared while open. The port steps the player directly, so its unused actor +state pointer/class/activity fields are not compared with DOS's `s_player` / +`s_attack` object representation. Player position, controls, inventory and +weapon timing are compared explicitly. Actor activity is compared as a boolean. + +`tests/fixtures/dos_demo_hashes.json` contains source identities and a SHA-256 +hash of the complete canonical frame for all 5,386 commands. It contains no +recorded commands, maps, textures, audio or executable bytes. Owned-data tests +assert every hash and every expected duration; another data revision is skipped +explicitly until its own reference is captured. Synthetic tests check repeatable +tracing and four-tic cadence. Existing Classic tests still exercise one/four-tic +host batching, input isolation, abort/focus behavior and malformed/missing demos. + +Example private workflow from the repository root: + +```sh +python3 scripts/demo_reference.py --data "$WOLF3D_DATA" \ + --output build/checks/dos-reference +SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy dosbox \ + -c 'config -set cpu cycles=100000' \ + -c 'mount c build/checks/dos-reference' -c c: \ + -c 'trace.exe nowait' -c exit + +gcc -std=c11 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -Isrc -I../cart/vendor/SDL/include tests/demo_trace.c \ + src/engine/*.c src/platform/*.c ../cart/vendor/SDL/build/libSDL3.a \ + -pthread -lm -o build/checks/demo-trace +build/checks/demo-trace "$WOLF3D_DATA" > build/checks/native-demo.csv +python3 scripts/compare_demo_traces.py \ + --dos build/checks/dos-reference/TRACE.BIN \ + --native build/checks/native-demo.csv +``` + +Raw DOS traces include original commands and map-derived state. Keep them and +private reference executables out of commits/distributions. The builder accepts +an ignored `build/` subdirectory or an external private output directory, refuses +non-empty destinations, and never writes into the original game-data directory. + +## Results and limits + +| Demo | Commands / tics | Final DOS/native health | Final ammunition / RNG index | +| --- | --- | ---: | --- | +| 0 | 691 / 2764 | 0 | 75 / 22 | +| 1 | 1899 / 7596 | 100 | 0 / 127 | +| 2 | 1140 / 4560 | 0 | 16 / 191 | +| 3 | 1656 / 6624 | 0 | 72 / 48 | + +Deaths on the final commands in demos 0, 2 and 3 are also present in the DOS +reference. They are not suppressed to satisfy the duration checks. + +Verification on Linux with the legitimate owned data: + +| Check | Result | +| --- | --- | +| `./build/tools/cart build --profile cart-sdl` | Passed | +| Strict full-application GCC C11, `-Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror` | Passed, including ASan/UBSan build | +| `WOLF3D_DATA=... python3 -m unittest discover -s tests -v` | **108 passed**, 407.772 s | +| Same complete suite with `SANITIZE=1`, `UBSAN_OPTIONS=halt_on_error=1` and instrumented `WOLF3D_BINARY` | **108 passed**, 931.948 s; no sanitizer findings | +| DOSBox timed/accelerated references; current runner/native comparison | All 5,386 command frames match | +| Synthetic repeatable trace, malformed clock/list/truncation checks, progress API | Passed | +| Door release, original corner/center rules, 16-bit timer wrap and timer-over-300 save round trip | Passed | +| Existing controlled finale/continuation tests for all six episodes | Passed in both full suites | +| CART SDL3 and desktop output-directory regressions | Passed | +| Linux X11/software-renderer five-frame E1M1 smoke, isolated preferences | Passed | +| Strict MinGW C11 full application and trace/Classic harness cross-links, SDL3 3.4.18 SDK | Passed | +| Wine native trace vs DOS | All 5,386 frame records match | +| Wine SDL dummy-video Classic owned-demo/progress/input-abort harness and application `--check-level` | Passed | + +The regular and sanitizer commands use private fixture/save directories; the +manual native smoke uses an isolated `XDG_DATA_HOME`. The owned audio sanitizer +case takes several minutes of CPU time. Native Windows, hardware audio/DOS +listening comparisons and a fresh Borland C executable build were not performed. + +Limits remain explicit: + +- This establishes equality of the listed simulation/visibility/grid fields for + these four recordings, this retail archive revision, view size 15 and silent + DOS reference settings. Other viewport sizes, releases and audio configurations + have not received equivalent DOS traces. It is not a full six-episode DOS + equivalence claim or a framebuffer/CRT comparison. +- DOS `UpdateFace()` skips RNG work while `GETGATLINGSND` is playing. The native + port retains its existing audio-independent gameplay RNG behavior. Enabled-DOS + sound timing and that potential synchronization difference remain unaudited; + ordinary SDL audio on/off independence continues to be regression-tested. +- Native HUD episode/floor numbering normalizes global demo map indices rather + than displaying DOS global numbers such as floor 38. Safe scaler/fizzle clipping + and remaining menu/high-score differences from the Classic audit remain. +- Windows results use MinGW and Wine; no physical Windows or DOS hardware test + is claimed. The original C engine was not rebuilt with Borland/Open Watcom. diff --git a/docs/MILESTONE7_VISUAL.md b/docs/MILESTONE7_VISUAL.md new file mode 100644 index 00000000..3f817448 --- /dev/null +++ b/docs/MILESTONE7_VISUAL.md @@ -0,0 +1,290 @@ +# Milestone 7: native high resolution and widescreen + +Implemented on `feature/7b-visual-foundation` for draft PR #10. Original remains +both the initial preference and the authoritative DOS gameplay renderer. There +is no separate Enhanced gameplay mode. No ECWolf source, replacement artwork, +commercial archives or captured commercial images are included. + +## Reference review + +Reviewed ECWolf's current upstream tree at +[`1bff92d43bc1c1b6e9c4c03f0fd3c7ae9c972f9e`](https://github.com/ECWolfEngine/ECWolf/tree/1bff92d43bc1c1b6e9c4c03f0fd3c7ae9c972f9e): +`sdlvideo.cpp` (`ScaleWithAspect`, logical presentation, `SetVSync`), +`v_video.cpp` (aspect correction), `wl_draw.cpp` (projection/ray traversal), +`wl_menu.cpp` (aspect and video selections), `r_2d/r_main.cpp` and +`g_wolf/wolf_sbar.cpp` (interface coordinates and status artwork). The useful +behaviours are separate world/UI geometry, horizontal expansion and explicit +video preferences. This implementation was written independently in C11 using +this port's existing ray intersections and SDL3 pipeline; ECWolf code was not +copied and its C++/modding framework is not a dependency. + +## Renderer and gameplay boundary + +`WL_RENDER_TARGET` owns no allocations. Every operation validates its pixels, +capacity, stride and bounded dimensions, including overflow and descriptor +corruption. Failed initialization preserves the previous descriptor. Native +scene rendering accepts 320..4096 by 200..2160 targets and caller-owned per-column +depth storage. The three fixed menu presets are 640×480, 1280×720 and 1920×1080. + +`WL_DRAW` shares its existing wall/door/pushwall intersection routine between +Classic and the native pass. Classic calls it with visibility marking enabled; +the additional pass cannot mark `spotvis`. Each native viewport column casts +its own ray. Perspective wall heights and sprite footprints use the native +projection; they are not enlarged Classic pixels. Original 64×64 wall samples, +sprite transparency posts (including opaque palette index zero), texture flips, +door leading-edge offsets, pushwall offsets and palette indices are retained. +Sprites sort stably far-to-near and test each column against wall distance. +Weapons retain their original two-half sprite anchoring and pixel aspect. + +The original 320×200 pass still runs at its existing points in simulation. That +is necessary because DOS rendering determines visibility, actor activation and +some pickups. The native pass reads actors, using local copies for original +rotation calculations, and changes no inventory, RNG, commands, clock, AI or +save state. Widescreen-visible actors still follow DOS activation rules. + +A presentation-only render serial invalidates cached native images after a +Classic redraw, including save/load at an identical game clock/framebuffer. +It is neither simulated nor serialized. Unchanged presentation is cached. +Targets, RGBA conversion storage, depth columns and SDL textures are reused. +Allocations occur on mode/resolution changes, not on ordinary frames. Invalid +settings and failed texture/allocation, filtering, VSync or fullscreen changes +retain the previous working settings. Automatic desktop changes stage a new +surface before releasing the old one; allocation failure keeps the old surface +and retries at most once per second. + +## Aspect, HUD and presentation + +`WL_AspectFit` fits with 64-bit products and commits its output only on success. +FOV validation rejects NaN, infinities, zero and unrepresentable results. The +original MinGW `isfinite` macro caused a strict conversion warning; bounded +ordered comparisons reject those values portably without narrowing doubles. + +High Resolution fits the selected aspect into its internal canvas, crops that +content rectangle for SDL presentation and letterboxes the physical output. +Auto aspect uses the current drawable dimensions, clamped to 4:3..32:9. Explicit +choices are 4:3, 16:9, 16:10, 21:9 and 32:9. Portrait/narrow windows letterbox. + +Vertical framing is fixed. Native focal length is based on corrected scene +height, the original viewport fraction and `(FOCALLENGTH+MINDIST)`. Width adds +rays on either side of the centre. For reference horizontal FOV `f`: + +``` +wide_fov = 2 * atan(tan(f / 2) * (aspect / (4 / 3))) +``` + +Tests compare exact central viewport pixels at equal heights across different +widths, independently of original HUD pixels. The original view sizes 4–19 are +retained; Change View still changes the world rectangle. The teal border and +bevel frame the expanded rectangle. The original status bar remains centred in +an independently aspect-correct 4:3 region; its outer areas are black. Health, +face, ammo, keys and weapon graphics retain their original positions/artwork. +Menus always use the original framebuffer through 320×240 logical presentation. + +Nearest texture sampling is fixed in the indexed renderer. The optional Linear +filter affects only final SDL texture presentation. Integer scaling uses whole +internal pixels for the active surface, falling back to aspect-preserving Fit +when the drawable is smaller than one surface. Original mode retains its +320×240 integer/fit behaviour. No OpenGL/Vulkan/shaders or alternate GUI is added. + +Resizable windows, borderless desktop fullscreen and asynchronous window-size +restoration retain the previous SDL state machine. Pixel sizes come from +`SDL_GetRenderOutputSize`, not window point dimensions. Auto resolution uses the +window's desktop display mode, preserving its ratio while bounding allocation +to 4096×2160. Fixed resolution remains independent of window size and DPI. + +## Display menu and configuration + +Control → Display has nine original-font rows: Fullscreen, Scaling, Window size, +Rendering, 3D resolution, Aspect ratio, VSync, Filter and Reset defaults. Arrows +and Enter change choices without restarting. Reset returns to windowed 960×720, +Fit, Original, fixed 640×480, Auto aspect, VSync off and Nearest. + +The additive schema remains version 1. Existing files without new keys retain +the defaults. Visual keys live in `[display]` alongside existing window options: + +```toml +[display] +fullscreen = false +integer_scaling = false +window_width = 960 +window_height = 720 +renderer = "original" # or "high_resolution" +render_width = 640 # fixed pairs: 640x480, 1280x720, 1920x1080 +render_height = 480 +render_auto = false # true selects bounded desktop resolution +aspect_ratio = "auto" # "4:3", "16:9", "16:10", "21:9", "32:9" +vsync = false +filter = "nearest" # or "linear", final presentation only +``` + +Unknown renderer/aspect/filter strings, invalid resolution pairs and wrong +value types fall back predictably. The existing atomic preference writer, +unsupported-file preservation, two control profiles and game-save format are +unchanged. An unsupported backend VSync request is reported and rejected. + +Alt+Enter switches fullscreen; F11 switches scaling. F12 captures an actual SDL +rendered BMP into `SDL_GetPrefPath(NULL,"wolf3d-revive")`, beside `config.toml`: +`~/.local/share/wolf3d-revive/` (or `$XDG_DATA_HOME`) on Linux and +`%APPDATA%\wolf3d-revive\` on Windows. Names include monotonic nanoseconds and +an existence check. Key repeats and key-up are consumed, focus loss is respected, +and F12 is reserved from custom gameplay bindings. Capture errors are reported +without ending gameplay. These locally generated images may contain commercial +art; do not commit/distribute them. + +## Audio investigation + +Compared `origin/master` with PR #9's branch +`origin/feature/audio-render-stall-buffer`: its current diff contains only +`docs/AUDIO_RENDER_STALL.md`. It describes an 80 ms experiment but makes **no +code change**. PR #9 was not merged. This branch tests the proposed buffer sizes +independently with test-only queue controls. + +Master fills 384-frame chunks to 24–32 ms on the main thread. A real ALSA/pulse +output here has 1024 frames at 48 kHz: **21.33 ms per device block**. A 24 ms +queue barely covers one block. Servicing between expensive render batches alone +reduced the user's crackling but did not eliminate it. + +The producer now primes before resuming the device and fills to the greater of +80 ms or two device periods plus 8 ms, with a 250 ms bound and silent failure for +unsupported device latency. Its 8 ms chunks can overshoot the target by less +than 8 ms. Synthesis uses the existing sample-based rational IMF clock, never +frame deltas. Rendering services the same main-thread producer between wall, +sprite, UI and conversion batches and before/after drawing. No audio thread, +sound-command reordering, RNG changes or extra simulation ticks were added. + +A dummy-device comparison injected a 60 ms blocking stall: the 24 ms policy had +0 queued bytes afterwards; the 80 ms policy retained 3072 bytes (16 ms). Three +1920×1080 frames with deliberately delayed render batches made 810 service calls +with **zero observed empty queues**; measured maximum service gap was about +3.2 ms in the final focused run. The user then listened through the real SDL +output at 1920×1080 and reported **“Sounds normal now.”** + +Latency cost: application queue targets are measured in input PCM frames: +24 ms before versus 80 ms here, approximately **56 ms extra queued output** at +this device period. These are application-buffer measurements, not microphone +or hardware end-to-end latency measurements. SDL/OS/device buffering adds delay. +Arbitrarily long OS/driver freezes can still underrun; this bounded main-thread +producer is not a hard real-time guarantee. + +## Verification and measurements + +Owned WL6 data was read from the local Steam installation. Automated fixtures +are synthetic; only hashes/trace summaries are tracked. No original archives, +reference source modifications or commercial captures are part of this change. + +| Check | Result | +| --- | --- | +| CART C11 SDL build | Passed | +| Full normal owned-data regression suite, after death correction | 115 passed, 461.480 s | +| Focused final visual suite (including all 60 maps) | 5 passed, 18.465 s | +| Full ASan/UBSan owned-data suite, initial Milestone 7 baseline | 115 passed, 992.864 s; no sanitizer diagnostics | +| Death correction ASan/UBSan focused visual suite | 5 passed, 72.641 s; no sanitizer diagnostics | +| CART SDL3 and desktop-directory regressions | Passed | +| Strict GCC C11 (`-Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror`) | Passed | +| Strict MinGW full app, aspect, renderer and demo-trace cross-links, SDL3 3.4.18 | Passed | +| Wine dummy/software renderer, settings/restarts, screenshots, failures and audio stress | Passed | +| Wine widescreen demo hashes | All 5,386 match DOS reference | +| Wine application `--check-level` | Passed | +| Native Linux X11/software fullscreen, window restoration, relative capture, focus and mode changes | Passed | +| Real SDL audio listening, High Resolution 1920×1080 | User confirmed normal playback | + +Focused coverage: + +- Target boundaries/overflow/padding/corrupted descriptors; aspect/FOV extremes. +- All 16 original view sizes at each fixed resolution, exact HUD composition, + extra geometry, depth sorting, transparency, opaque zero, clipping and weapons. +- Additional aspect/view combinations at 3440×1440, 3840×1080 and 4096×2160. +- All 60 owned maps rendered natively at 640×480 / 16:9 in four cardinal + directions, checking unchanged original framebuffer and RNG. +- Original framebuffer hashes: 32 captures, views 4–19 initially and at tic 60, + captured from the pre-modern renderer and unchanged by these changes. +- All four owned DOS recordings with a native widescreen render after every + command, including interspersed 1280×720 and 1920×1080 passes. Expected traces + remain the existing 6G reference (default view 15, silent reference settings). +- Player/actor/visibility/RNG/clock and serialized save payload isolation. +- SDL resize/tiny windows, fullscreen return, Auto desktop, mode switching, + three full SDL restarts, preference round trips, filter/VSync failures, + allocation/texture rollback, F12 capture/repeat consumption and audio stalls. +- Native X11/software 1280×720 captures of widescreen gameplay and the Display + menu inspected locally. Actual 1920×1080 SDL audio listening confirmed by user. + +Owned-E1M1 benchmark (`tests/render_benchmark.c`), view 19, 20 native scene passes, GCC `-O2`, while +other regressions ran; **excludes SDL upload, presentation and simulation**: + +| Canvas | Mean scene ms | Persistent CPU indexed + RGBA bytes | +| --- | ---: | ---: | +| 640×480 | 1.71 | 1,536,000 | +| 1280×720 | 4.49 | 4,608,000 | +| 1920×1080 | 9.43 | 10,368,000 | +| 3440×1440 | 20.74 | 24,768,000 | +| 3840×1080 | 17.57 | 20,736,000 | +| 4096×2160 | 79.51 | 44,236,800 | + +Repeat the scene benchmark with your own data and local SDL SDK: + +```sh +gcc -std=c11 -O2 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -Isrc -I../cart/vendor/SDL/include tests/render_benchmark.c \ + src/engine/*.c src/platform/data_file.c src/platform/save_file.c \ + ../cart/vendor/SDL/build/libSDL3.a -pthread -lm -o build/checks/render-benchmark +build/checks/render-benchmark "$WOLF3D_DATA" +``` + +These measurements are not frame-rate guarantees. The normal CART profile has +no optimization flag; the strict unoptimized matrix measured roughly 3–17 ms +at 640×480..1920×1080 and 71–104 ms at 4096×2160, depending on aspect/view/scene. +Depth storage adds 16 KiB; SDL texture/driver allocations add further memory +(approximately another four bytes per canvas pixel for a texture). Replacement +can briefly hold two surfaces. No per-frame surface allocation is required. + +Measured full-application peak RSS using `os.wait4` on Linux, SDL dummy/software, +1280×720 window, 200 E1M1 presentation frames and `--no-audio`: **13,880 KiB +Original** versus **27,652 KiB High Resolution at 1920×1080**. Elapsed times +were 2.315 s and 8.711 s respectively; these include the main loop's 4 ms waits, +simulation, fades and rendering and are not a renderer-only benchmark. + +## Death transition correction + +The initial death fallback switched the world content to a centred 4:3 Classic +image, visibly narrowing a widescreen scene. Death now retains the same native +viewport, projection, teal border and independently centred HUD through the +turn toward the killer, red fizzle, red hold and respawn. The weapon disappears +on death as in the original renderer. + +A read-only death phase/cursor query exposes the existing presentation progress. +The native renderer replays the original 17-bit polynomial up to that cursor, +then maps the mask across the entire native viewport. It never advances the +game's fizzle cursor, RNG or timer. The SDL upload cache also watches death +phase/cursor changes: a Classic source pixel already red can leave framebuffer +bytes unchanged while native fizzle coverage still needs updating. + +Regression coverage checks all three fixed resolutions, all five explicit +aspects plus Auto in a 16:9 window, and every death phase through respawn. The +controlled death takes 290 original ticks in each case. Checks include native +viewport edges outside the former 4:3 world, full red coverage, stable SDL +presentation proportions, cursor-driven uploads with an unchanged Classic +framebuffer, and read-only frame/RNG/clock/cursor behaviour. Native X11 captures +of rotation, fizzle, red hold and respawn were inspected locally. Original +framebuffer hashes remain unchanged. Follow-up checks passed: full normal suite +115/115, focused visual suite 5/5 normally and under ASan/UBSan, strict CART C11, +strict MinGW full application/render harness, Wine owned-data death/Auto-aspect +cases and native X11 capture inspection. The death fix did not require changes +to the original death simulation or saved-game format. + +## Verified limits and deferred work + +- Physical Windows, Windows audio, real ultrawide panels, multiple-monitor + migration and a physical DPI scale greater than 1× are not claimed. Wine and + dummy dimensions cover API behaviour, not every OS/driver. +- VSync may be unsupported or ineffective on a backend; SDL rejection is shown. + Linear presentation can soften original pixel artwork, by choice only. +- Scripted victory presentation uses the original composited framebuffer at + higher display scale. Normal world geometry and death presentation are native. +- The original 0.1-degree ray tables and source-art resolution remain visible at + high pixel counts. No antialiasing, new artwork, increased vertical FOV or + replacement rendering API is introduced. Very high resolution is CPU costly. +- Wider visibility does not expand DOS AI activation/pickup visibility. Full + campaign playthroughs and DOS equivalence beyond established 6G traces/view + settings are not newly claimed. +- No merge, push, PR #8 reopening or PR #9 merge was performed. PR #10 remains + draft. `master`, `WOLFSRC/` and original archives remain unchanged. diff --git a/docs/MILESTONE8.md b/docs/MILESTONE8.md new file mode 100644 index 00000000..85c712ce --- /dev/null +++ b/docs/MILESTONE8.md @@ -0,0 +1,314 @@ +# Milestone 8: high-refresh presentation + +Status: implementation complete; local verification results below. PR #11 stays draft; +physical high-refresh and audio output measurements are still required. +No changes to WOLFSRC, game assets, gameplay RNG, movement, collision, combat +or enemy thinkers are part of this milestone. No new backend or audio thread. + +## Architecture and exact behaviour + +```mermaid +flowchart TD + A[SDL events: keys, mouse, focus, window] --> B[Main-thread loop] + C[SDL monotonic nanoseconds] --> B + B --> D[Consume at most 8 outstanding rational 70 Hz deadlines] + D --> E[DemoLoop / GameStep] + E --> F[Original simulation and Classic visibility/framebuffer pass] + F --> G[Capture immutable previous/current presentation snapshots] + B --> H[Audio pump] + B --> I{Presentation deadline due?} + I --> J[Sample matching snapshot poses with clamped alpha] + J --> K[Native indexed rays / sprites / centred original HUD] + K --> L[Palette conversion / texture upload / SDL present] + K --> H + L --> M[Next deadline: render start plus monitor period] + N[Window current SDL display mode; desktop fallback] --> M + M --> O[Sleep until earliest simulation/presentation deadline, max 4 ms] + O --> B +``` + +The simulation scheduler consumes each deadline exactly once, using integer +rational 70 Hz conversions instead of a rounded 14 ms timestep. The eight-tick +batch limit bounds work between event polls; remaining debt stays in +`completed_tick` and is consumed on subsequent iterations. Simulation time is +never advanced merely because a presentation frame was drawn. Events are +sampled once per outer iteration; held controls apply to subsequent ticks, +press edges and mouse deltas are consumed by the original per-tick input path. +Input events are not retroactively timestamped through a stall. + +Classic keeps its original authoritative renderer, framebuffer, and 4 ms outer +sleep, with no interpolation. It intentionally shares the exact deadline +scheduler: returning to the old outer-clock call would reintroduce `MAXTICS` +debt truncation after stalls and mode-switch ambiguity. `GameStep` retains its +legacy bounded elapsed-time API for existing direct callers; the application +passes individual deadlines. Paused/menu/fade ticks continue to run the UI, +not gameplay. Save/load and resume rebase the game's clock and snapshots. +Original demos still consume a command every **four** 70 Hz ticks, including +their original four-tic movement, AI and RNG semantics. + +Smooth Rendering is active only with High Resolution. The Display menu has +**no manual FPS selection**, and config output has no `presentation_fps` key. +Old TOML files may contain that unknown key; it is ignored on load and removed +on the next valid save, while `smooth_rendering` is preserved. Invalid/future +configuration files retain their existing preservation policy. + +The video platform queries `SDL_GetCurrentDisplayMode` for +`SDL_GetDisplayForWindow(window)` each scheduling iteration. Invalid/missing +refresh values fall back to the desktop mode, then 60 Hz. Rates are continuous +floating point values (59.94 Hz is not rounded to 60), capped at 240 FPS. +No table of supported refresh presets is used. Changing displays, fullscreen +mode, or refresh updates the next deadline immediately; Auto desktop render +size continues to use the existing staged surface allocation/retry path. + +Presentation deadlines use a fresh timestamp after simulation, anchored at +render start. Rendering/upload/present time is subtracted from the available +period; an over-budget frame becomes immediately eligible without replaying +missed frames. When SDL reports VSync enabled and the last present blocked for +at least half a monitor period, VSync owns monitor pacing and software enforces +only the 240 FPS ceiling. Nonblocking/unsupported VSync retains the monitor +software limit. There is no extra full-period sleep after a blocking present. +Sleep is bounded to 4 ms for input and audio service; it does not busy-spin. +VSync/VRR/compositor behaviour still requires physical display validation. + +## Snapshot audit and corrections + +Snapshots contain camera position/angle; actor allocation identities, poses, +sprite state and facing; door geometry/positions; tiles/statics; pushwall state; +weapon frame; level/view identity; ceiling colour; death phase/cursor; and +instantaneous death/victory/demo flags. The original HUD/framebuffer and palette +are composited live so pickups, weapon animation and UI events remain instant. +The renderer reads presentation data without writing authoritative objects, +visibility, clock, palette, input or RNG. + +Sampling adds one simulation interval of latency and clamps alpha to [0,1]. +Normal play interpolates between 70 Hz captures; demos between four-tic command +captures. Camera and actor facing use the shortest angle arc. Allocation +identities prevent blending newly spawned/reused slots; removed actors vanish +immediately. Sprite state changes are instantaneous. Large position jumps, +level/view changes, regressing clocks, load/resume, death/respawn and demo +transitions snap/reset rather than interpolating unrelated states. Death +rotation can interpolate; the fizzle and victory presentation remain discrete. + +Corrections made after reviewing all 21 original PR commits: + +- New or replaced door indices snap unless both snapshots match geometry, + orientation and lock. They previously blended against unrelated old data. +- Pushwalls interpolate only within the same tile or a valid cardinal crossing. + At a crossing, only affected pushwall/reservation cells rewind; the previous + whole-map copy could resurrect a just-opened door or unrelated changed tile. +- Actor facing now interpolates across direction wrap. Ceiling, death progress + and overlay flags come from the supplied snapshot rather than the live world. +- Frame pacing uses fresh render-start timestamps, preserves fractional monitor + rates, falls back from invalid current modes, and accounts for blocking VSync. +- Sky/floor are filled by contiguous rows. Wall spans alone use column writes, + with a reciprocal texture scale instead of division for every wall pixel. + Original wall intersections, texture pages and Classic drawing are unchanged. + +The original PR's groundwork, integration, refresh-policy, menu/config and +regression commits were all inspected, including the intermediate split changes +and the malformed literal-newline HUD comment later fixed by its integration +commit. Review range: `89cfdf8` through `7cc05a3`, 21 commits, relative to the +PR base `origin/master` at the start of this work. + +## HUD and native geometry + +Palette index 127 fills the full native gameplay scene, including status-bar +side gutters. The centred original 4:3 status artwork is then copied unchanged. +Native bevels frame the world viewport. Letterboxing outside the selected +scene remains black. Tests compare every HUD/gutter pixel across all five +aspects (4:3, 16:9, 16:10, 21:9, 32:9), all fixed render presets and larger +canvases, plus the original framebuffer hash oracle. Window resizing, tiny +windows, fullscreen, Auto desktop resolution, filtering, death/respawn, +allocation failures and transactional display-setting failures have SDL tests. + +## Reproducible validation + +All commands use owned WL6 assets externally; no commercial assets or captures +are committed. Build artifacts and raw logs are under ignored `build/checks/`. + +```sh +export WOLF3D_DATA="$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" +export SDL_SDK=../cart/vendor/SDL + +gcc -std=c11 -O2 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -Isrc -I"$SDL_SDK/include" src/main.c src/engine/*.c src/platform/*.c \ + "$SDL_SDK/build/libSDL3.a" -pthread -lm -o build/checks/wolf3d-revive-m8 +WOLF3D_BINARY="$PWD/build/checks/wolf3d-revive-m8" \ + python3 -m unittest discover -s tests -v + +# Instrument the full app as well as the harnesses; the SDL static SDK is not +# itself sanitizer-instrumented. +gcc -std=c11 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -fsanitize=address,undefined -fno-omit-frame-pointer -g \ + -Isrc -I"$SDL_SDK/include" src/main.c src/engine/*.c src/platform/*.c \ + "$SDL_SDK/build/libSDL3.a" -pthread -lm -o build/checks/wolf3d-revive-m8-asan +SANITIZE=1 CC="gcc -O1" UBSAN_OPTIONS=halt_on_error=1 \ + WOLF3D_BINARY="$PWD/build/checks/wolf3d-revive-m8-asan" \ + python3 -m unittest discover -s tests -v +``` + +Validation on 2026-11-03 (Australia/Adelaide): + +| Check | Result | +| --- | --- | +| GCC C11 `-O2`, conversion/shadow/pedantic warnings, `-Werror` | Passed, full application and profiling harness | +| CART `cart-sdl` build | Passed | +| Application Smooth Rendering smoke, three fixed resolutions, VSync off/on, old FPS key | All six passed; migration persisted | +| Complete Linux suite, owned Steam WL6 | **119 tests passed**, 454.182 s | +| Complete ASan/UBSan suite, harnesses `-O1`, instrumented full app | **119 tests passed**, 993.598 s; no sanitizer findings | +| DOS reference, Classic and interpolated native pass | **5,386/5,386 match** in each Linux path | +| Classic framebuffer hash oracle | Exact reference match | +| Configuration persistence/obsolete FPS migration | Passed | +| Eight refresh rates / 140-tick save equivalence | Passed, 60/75/90/120/144/165/180/240 | +| MinGW x86_64 full application and renderer/demo harnesses, `-Werror` | Passed (SDL 3.4.18 development SDK) | +| Wine `--check-level`, owned renderer/Auto/fullscreen/failures/audio | Passed | +| Wine rational clock, interpolation at all eight rates and save equivalence | Passed | +| Wine interpolated DOS reference | **5,386/5,386 match**, counts 691/1899/1140/1656 | +| Native Linux X11/OpenGL renderer/resize/fullscreen, all 60 maps | Passed | +| HUD visual inspection | 16:9 and 32:9 captures inspected; teal gutters, centred artwork and bevels correct | + +Logs: `m8-suite.log`, `m8-asan-final-suite.log`, `m8-wine-complete.log`, `m8-native-final.log`, +`m8-presentation-final.log`, `m8-presentation-final-asan.log`, +`m8-wine-presentation-final.log`, `m8-render-final.log`, +`m8-render-final-asan.log`, and `m8-main-smoke.log` under `build/checks/`. Synthetic interpolation +covers slot reuse/removal, unmatched doors, all cardinal pushwall crossings +and stops, teleports, angle wrap, death, pause/resume, load and level resets. +Tests retain exact original four-tic demo state and byte-identical game saves +across independent render rates. + + +## Benchmark harness + +`tests/presentation_benchmark.c` measures four seconds per canvas at 640×480, +1280×720 and 1920×1080, view 19, owned E1M1, including simulation, main-thread +audio, indexed rendering, RGBA conversion, upload and SDL present. It reports +actual elapsed FPS, mean/p95/p99 interval, variance, CPU, processed/due ticks, +game clock, allocations and audio empty-queue observations. Optional profiling +is compiled out of normal builds. Capture cost is amortised per presentation; +sampling, rays/walls, sprites, conversion, upload and present have separate +counters. Linked SDL allocation calls are observed by the optional linker wrappers. +The frame path allocates no engine surfaces after warmup; SDL may allocate. + +```sh +gcc -std=c11 -O2 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -DWOLF3D_BENCHMARK -DWOLF3D_ALLOC_PROFILE \ + -Isrc -I"$SDL_SDK/include" tests/presentation_benchmark.c \ + src/engine/*.c src/platform/*.c "$SDL_SDK/build/libSDL3.a" -pthread -lm \ + -Wl,--wrap=malloc,--wrap=calloc,--wrap=realloc \ + -o build/checks/presentation-benchmark8 +SDL_VIDEODRIVER=dummy SDL_RENDER_DRIVER=software SDL_AUDIODRIVER=dummy \ + build/checks/presentation-benchmark8 "$WOLF3D_DATA" +``` + +The optional second argument overrides the harness target for synthetic rate +experiments only. It is not a player setting or proof of a monitor's refresh. +Set `M8_VSYNC=1` to request VSync; a backend that rejects it fails the harness +explicitly. Remove dummy driver overrides for a native desktop measurement. + +## Measured results + +Host: 13th Gen Intel Core i5-1340P, Linux, reused sibling SDL static SDK. +Native desktop: X11/OpenGL, SDL-reported **59.880 Hz**, 1280×720 window; +SDL dummy audio. Software path: dummy video/software renderer, 60 Hz fallback. +Four seconds per canvas after at least 300 ms / 20 frames of cache and fade +warmup. ASan regressions were running concurrently on other cores; thermal, +compositor and scheduling load affect these short measurements. These are +observed present-call rates, not measurements of scanout or motion-to-photon +latency. No physical high-refresh display was available. + +| Path | Canvas | Actual FPS | Mean ms | p95 ms | p99 ms | Variance ms² | CPU % | +| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | +| X11, VSync off | 640x480 | 59.19 | 16.877 | 18.231 | 18.817 | 0.7760 | 21.0 | +| X11, VSync off | 1280x720 | 59.22 | 16.872 | 19.264 | 21.166 | 2.5923 | 45.7 | +| X11, VSync off | 1920x1080 | 57.63 | 17.351 | 21.008 | 24.116 | 3.3509 | 76.8 | +| X11, VSync on | 640x480 | 59.94 | 16.682 | 17.603 | 18.353 | 0.4541 | 15.9 | +| X11, VSync on | 1280x720 | 59.90 | 16.683 | 17.644 | 17.925 | 0.5228 | 38.3 | +| X11, VSync on | 1920x1080 | 56.36 | 17.743 | 23.775 | 25.578 | 7.0127 | 78.6 | +| Dummy/software | 640x480 | 59.49 | 16.808 | 18.006 | 19.406 | 0.9115 | 53.5 | +| Dummy/software | 1280x720 | 59.49 | 16.809 | 18.070 | 18.873 | 1.0664 | 36.9 | +| Dummy/software | 1920x1080 | 56.65 | 17.652 | 18.633 | 19.187 | 0.3393 | 100.2 | + +Additional **diagnostic target overrides**, same 59.88 Hz desktop, VSync off: +these measure presentation-call capacity, **not high-refresh scanout**. Neither +144 nor 240 FPS was sustained at the corresponding requested target. + +| Harness target | Canvas | Actual FPS | Mean ms | p95 ms | p99 ms | Variance ms² | CPU % | +| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | +| 144 | 640x480 | 139.06 | 7.183 | 8.658 | 9.602 | 1.0245 | 55.1 | +| 144 | 1280x720 | 124.64 | 8.022 | 12.521 | 13.941 | 3.6375 | 92.3 | +| 144 | 1920x1080 | 70.90 | 14.105 | 21.240 | 23.985 | 9.3986 | 99.8 | +| 240 | 640x480 | 213.41 | 4.686 | 5.971 | 6.731 | 0.5531 | 88.3 | +| 240 | 1280x720 | 138.96 | 7.196 | 12.356 | 13.678 | 5.2090 | 100.2 | +| 240 | 1920x1080 | 71.31 | 14.023 | 22.729 | 25.943 | 16.3265 | 100.1 | + +Raw logs: `m8-native-target144.log`, `m8-native-target240.log`. The product +still derives its rate automatically; only the benchmark harness accepts an +override. All six runs preserved exact processed game-tick counts, retained at +most one outstanding tick at exit, and observed zero empty audio queues. + +Component means, X11 VSync off, milliseconds amortised per presentation: + +| Canvas | Rays + walls | Sprites | Capture | Sample | RGBA convert | Upload | Present | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 640x480 | 0.6102 | 0.5024 | 0.0078 | 0.0059 | 0.5151 | 0.2843 | 0.2253 | +| 1280x720 | 2.1129 | 0.5484 | 0.0079 | 0.0059 | 1.4925 | 0.7576 | 0.2446 | +| 1920x1080 | 4.2321 | 0.5525 | 0.0078 | 0.0054 | 3.0173 | 1.1494 | 0.2161 | + +The 640×480 VSync run spent 14.29 ms in present and achieved 59.94 FPS; +1280×720 spent 9.41 ms and achieved 59.90 FPS. This verifies that the tested +blocking path does not add a second monitor-period wait. At 1920×1080 this +machine did not sustain monitor refresh in these runs. Higher targets are +therefore not claimed at 1080p. The initial scene-only 20-pass runs measured +9.55 ms before and 6.24 ms after the wall-fill optimisation; those are short +microbenchmarks, not end-to-end performance guarantees. + +Every measured game-clock increment exactly equals the processed deadline +count (279 or 280 ticks per four-second measurement). At exit, zero or one +additional tick was due: this is outstanding scheduler debt immediately after +the final render/wait, not a discarded tick. Exact long-term 700 ticks per +10 seconds and bounded stall-debt consumption are separately asserted by the +clock regressions. The application does not flush gameplay debt on shutdown. + +Peak child RSS, including warmed SDL/driver allocations over all three canvases: +176,524 KiB X11 VSync off; 170,140 KiB X11 VSync on; 30,588 KiB dummy/software. +Persistent indexed + RGBA surface budgets are 1,536,000 / 4,608,000 / 10,368,000 +bytes, plus texture/depth/snapshot storage. The X11 VSync-off run intercepted +3,570 / 3,102 / 2,522 allocation calls over each four-second interval. These +include statically linked SDL calls; dynamically loaded driver/libc-internal +allocations are outside the linker wrappers. Engine surfaces are reused, but +the overall SDL frame path is not allocation-free. CPU is process CPU time, +including SDL threads; 100% corresponds to one fully occupied logical CPU. + +Raw benchmark and RSS records are `m8-native-benchmark.log`, +`m8-native-vsync-benchmark.log`, `m8-benchmark60-final.log`, and their matching +`*-memory.log` files. Captures stay in ignored `build/checks/m8-native/`. + +## Audio findings and remaining limits + +All fifteen full-path measurements observed **zero empty SDL input queues**. +The owned renderer stress serviced audio 888 times across long frames with +zero empty queues; maximum observed gaps in the final audio-active transition runs were +2.40 ms native X11 and 3.05 ms Wine. The 60 ms unserviced stall emptied the deliberately short 24 ms control +queue, while the production 80 ms queue retained audio. Existing regressions +also cover music/effects playback, focus and pause/resume state, and repeated +SDL lifecycle. Owned renderer tests now keep audio active across resizing and +fullscreen changes, closing/reopening audio around complete SDL recreation +in the same order as the application. The effect-request test measured +**80.00 ms** of existing input audio queued before synthesis; device/OS +latency is additional. These tests justify retaining the main-thread producer. + +The main-thread producer retains an 80 ms floor, two device periods plus 8 ms +headroom, and a 250 ms maximum. Rendering services audio between bounded ray, +sprite, conversion and fizzle batches, and before/after presentation. No audio +thread was introduced. A device/OS stall longer than the bounded queue can +still underrun; the producer cannot service audio during a blocking driver call. +An empty SDL input queue is an observation, not a hardware underrun counter. + +Actual speaker input-to-sound latency and physical underruns cannot be inferred +from dummy audio queues. Queue depth implies latency as well as stall tolerance; +a listening/loopback test on the user's output device remains necessary. +Physical 75–240 Hz, multi-monitor migration, live refresh changes, VRR, +other fullscreen compositors, focus/pause transitions with real audio, and physical +Windows hardware remain acceptance checks. Synthetic rate and SDL transition +regressions do not establish those hardware results. No 144 or 240 FPS +performance guarantee is made. diff --git a/docs/MILESTONE9.md b/docs/MILESTONE9.md new file mode 100644 index 00000000..7215fca2 --- /dev/null +++ b/docs/MILESTONE9.md @@ -0,0 +1,309 @@ +# Milestone 9: bounded software rendering and SDL scaling + +Implementation and local verification completed on 2026-11-03 +(Australia/Adelaide). Physical 4K, high-refresh, multi-monitor and audio-device +validation remain hardware acceptance checks; synthetic outputs do not establish +those results. The latest master README simplification is preserved verbatim. + +## Rendering policy + +Auto fits the active desktop display's aspect into a canvas bounded by the +display size and **1920×1080**. SDL3 presents that indexed software-rendered +image, converted to an RGBA streaming texture, at the actual drawable size. +There is no dynamic resolution policy, GPU raycaster or additional backend. +The existing manual 640×480, 1280×720 and 1920×1080 settings remain available. + +| Desktop display | Auto canvas | +| --- | --- | +| 3840×2160 / 2560×1440 / 1920×1080 | 1920×1080 | +| 1280×720 | 1280×720 | +| 1600×1200 | 1440×1080 | +| 3440×1440 | 1920×803 | +| 3840×1080 | 1920×540 | +| 1080×1920 | 607×1080 | + +Auto aspect still follows drawable pixels, bounded to 4:3..32:9. Explicit aspect +choices fit into the internal canvas and SDL letterboxes the physical output. +Vertical world framing, centred original HUD artwork and palette-index-127 teal +gutters are retained. Nearest-neighbour filtering remains the default: 1080p +fills a 16:9 4K drawable at exactly 2×. Linear filtering remains optional. +Integer scaling retains its aspect-preserving Fit fallback for small windows. +Menus use the original 320×200 framebuffer with 320×240 logical presentation. + +Desktop dimensions and drawable dimensions have separate purposes. Window +resizes change presentation/aspect without reallocating an unchanged canvas. +Fullscreen remains SDL desktop fullscreen. Monitor migration stages a new +surface only if the bounded internal dimensions change; 4K↔1440p needs no +replacement. Allocation/texture failures keep the old surface and retry at most +once per second. Filtering changes reuse the surface. Fixed manual resolutions +remain independent of desktop dimensions and DPI. + +## Measured optimisation and pacing review + +The full SDL benchmark identified rays/walls and palette conversion as the main +1080p costs, with sprite drawing a smaller repeated cost. Two portable C11 loop +changes were retained: + +- Sprite texel row bounds are calculated once per shape. Wall-depth clipping + finds visible horizontal runs once per source column; texel rectangles use + contiguous row fills. Original half-sprite anchoring, floor rounding, + transparency, opaque index zero and far-to-near ordering remain exact. +- Palette conversion builds 256 RGBA words from bytes, preserving byte order + on either endian architecture. Aligned stores write one word per indexed + pixel. The VGA six-to-eight-bit expansion and alpha 255 remain exact. + +No decoded-sprite cache, per-frame engine allocation, new configuration, +renderer replacement or simulation change was needed. Wall intersections and +column sampling remain unchanged. Existing contiguous sky/floor fills and +reciprocal wall texture scaling from Milestone 8 are retained. SDL texture +uploads still copy the persistent RGBA buffer; replacing them with texture locks +was not justified by these measurements. The native image cache skips ray, +sprite, conversion and upload work for unchanged non-interpolated scenes. + +The Milestone 8 scheduler was reviewed and retained. Simulation consumes +rational 70 Hz deadlines in bounded batches without dropping outstanding ticks. +Smooth presentation samples immutable snapshots independently of simulation; +demos retain their original four-tick commands. Fresh render-start deadlines +subtract rendering cost, do not replay missed presentations, and account for +actually blocking VSync without an extra monitor-period delay. Input and audio +service waits remain bounded to 4 ms. Existing tests cover fractional refresh, +60/75/90/120/144/165/180/240 Hz simulation equivalence, stalls, save equivalence, +pause/load and presentation resets. Rendering continues to pump audio between +bounded work batches. No pacing rewrite was necessary. + +## Regression evidence + +The native oracle was captured from the pre-optimisation branch (`835bbff`, +with master's README-only merge) before changing the renderer. It covers all +60 maps, five canvases (including 1920×803 and 1920×540), all five explicit +aspects, varied camera angles and view sizes 4/19: **1,500 exact indexed hashes**. +`tests/fixtures/native_render_hashes.csv` contains hashes only. Owned asset +identities are checked before comparing either the native or Classic oracle. +No commercial assets or captures are committed. + +Additional SDL regressions simulate desktop changes through the production +Auto path. They check actual texture dimensions, creation counts, allocation +and texture rollback, retry throttling, same-size reuse and linear/nearest +selection. A 3840×2160 dummy/software capture is checked against every pixel of +the 1920×1080 indexed renderer after palette expansion and exact 2× nearest +scaling. This also checks HUD, gutters and RGBA colour reproduction end to end. +Portrait, extreme integer dimensions, invalid inputs and unchanged outputs on +failed Auto size calculations have unit coverage. + +| Check | Result | +| --- | --- | +| GCC C11 `-O2`, pedantic/conversion/shadow warnings, `-Werror` | Full application and profiling harness passed | +| CART `cart-sdl` build | Passed | +| Full normal Linux suite, owned WL6 | **120 passed**, 469.055 s; no skips | +| Full ASan/UBSan suite, harnesses/application `-O1` | **120 passed**, 943.235 s; no sanitizer findings or skips | +| Final focused rendering suite after diagnostic corrections | **6 passed**, 53.109 s | +| Classic framebuffer oracle | Exact match at all 16 original view sizes | +| Native pixel oracle | **1,500/1,500 exact hashes**, normal and sanitizers | +| DOS reference demos, Classic and interpolated native | **5,386/5,386 commands match in each path**, normal and sanitizers | +| Refresh-rate/save equivalence and stall retention | Passed at all eight existing test rates | +| Save/load, configuration, keyboard/mouse, display, audio and simulation regressions | Passed in full suites | +| MinGW x86_64 full app and renderer harness, strict `-Werror` | Passed, SDL3 3.4.18 SDK | +| Wine owned-data renderer/settings/Auto/fullscreen/failure/audio tests | Passed, including exact synthetic 4K pixel check | +| Native X11/SDL OpenGL renderer, resizing/fullscreen/Auto, all 60 maps | Passed; oversized-window limitation reported explicitly | +| Native/Wine audio render stress | 888 services, zero empty queues; maximum gaps 1.98 / 2.96 ms | +| Final diff and original sources | `git diff --check` passed; `WOLFSRC/` unchanged; README identical to master | + +Full logs are `suite.log`, `asan-suite.log`, `render-final.log`, +`native-verified.log`, `wine-final.log` and `cart.log` under ignored +`build/checks/m9/`. Synthetic 4K software-presentation audio observations from +the benchmark are separate from the passing bounded-render stress test; see +the measurements below. + +## Reproduction + +Use owned WL6 data outside the repository and a local SDL3 SDK: + +```sh +export WOLF3D_DATA="$HOME/.steam/steam/steamapps/common/Wolfenstein 3D/base" +export SDL_SDK=../cart/vendor/SDL +mkdir -p build/checks/m9 + +gcc -std=c11 -O2 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -Isrc -I"$SDL_SDK/include" src/main.c src/engine/*.c src/platform/*.c \ + "$SDL_SDK/build/libSDL3.a" -pthread -lm -o build/checks/m9/wolf3d-revive +WOLF3D_BINARY="$PWD/build/checks/m9/wolf3d-revive" \ + python3 -m unittest discover -s tests -v + +# Instrument the application as well as harnesses. SDL itself is not instrumented. +gcc -std=c11 -O1 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -fsanitize=address,undefined -fno-omit-frame-pointer -g \ + -Isrc -I"$SDL_SDK/include" src/main.c src/engine/*.c src/platform/*.c \ + "$SDL_SDK/build/libSDL3.a" -pthread -lm -o build/checks/m9/wolf3d-revive-asan +SANITIZE=1 CC="gcc -O1" UBSAN_OPTIONS=halt_on_error=1 \ + WOLF3D_BINARY="$PWD/build/checks/m9/wolf3d-revive-asan" \ + python3 -m unittest discover -s tests -v + +gcc -std=c11 -O2 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -DWOLF3D_BENCHMARK -DWOLF3D_ALLOC_PROFILE \ + -Isrc -I"$SDL_SDK/include" tests/presentation_benchmark.c \ + src/engine/*.c src/platform/*.c "$SDL_SDK/build/libSDL3.a" -pthread -lm \ + -Wl,--wrap=malloc,--wrap=calloc,--wrap=realloc \ + -o build/checks/m9/presentation-benchmark +SDL_AUDIODRIVER=dummy build/checks/m9/presentation-benchmark "$WOLF3D_DATA" +M8_VSYNC=1 SDL_AUDIODRIVER=dummy \ + build/checks/m9/presentation-benchmark "$WOLF3D_DATA" +# Optional controls; neither is a player setting. +M9_NO_SMOOTH=1 SDL_AUDIODRIVER=dummy \ + build/checks/m9/presentation-benchmark "$WOLF3D_DATA" +# Diagnostic target, not a high-refresh scanout test. +SDL_AUDIODRIVER=dummy \ + build/checks/m9/presentation-benchmark "$WOLF3D_DATA" 144 +``` + +## Before/after measurements + +Host: Intel Core i5-1340P, Linux, GCC 14.2.0 C11 `-O2`, static SDL3 +3.5.0 development SDK (`08b9c5539`), +owned E1M1, view 19. Each canvas runs for four seconds after at least 300 ms / +20 frames of warmup. Final harness polls events during warmup and records +actual drawable pixels. Baseline uses the same final harness and build flags, +replacing only `WL_RENDER.c` and `sdl_video.c` with their `835bbff` versions. +Copies were built with `-Isrc/engine -Isrc/platform` in addition to the commands +above. Thus this pair measures the loop changes, with the Auto cap present in +both builds. The cap itself reduces a 4K scene's software pixel count and +indexed+RGBA storage by 75% (41,472,000 to 10,368,000 bytes), independently of +these measured loop savings. + +Measurements are serial, with the ASan regression suite active on other cores. +Thermals, OS scheduling and compositor load affect these short runs. FPS is +present-call throughput; it does not measure scanout or motion-to-photon +latency. CPU is process CPU time, including SDL threads; 100% is one logical +CPU. Indexed+RGBA storage is 1,536,000 / 4,608,000 / 10,368,000 bytes for the +three presets, plus SDL texture/depth/snapshot storage. SDL still allocates in +its frame path; intercepted allocation counts are in the raw logs. Engine +surfaces are retained after warmup. + +X11 / SDL OpenGL presentation, 1280×720 drawable, Smooth Rendering on, +VSync off, monitor target 59.880 Hz. SDL's accelerated texture presentation +is used by the existing backend; the world renderer remains CPU-only. + +| Internal | Version | FPS | Mean ms | p95 ms | p99 ms | CPU % | +| --- | --- | ---: | ---: | ---: | ---: | ---: | +| 640x480 | Before | 59.25 | 16.860 | 17.776 | 18.687 | 19.4 | +| 640x480 | After | 59.24 | 16.855 | 17.954 | 19.134 | 18.5 | +| 1280x720 | Before | 59.22 | 16.866 | 18.715 | 19.706 | 41.1 | +| 1280x720 | After | 59.25 | 16.878 | 19.350 | 20.895 | 39.3 | +| 1920x1080 | Before | 55.70 | 17.953 | 24.037 | 25.782 | 81.2 | +| 1920x1080 | After | 58.38 | 17.129 | 19.954 | 23.115 | 69.4 | + +At 1080p the observed sprite cost fell from 0.624 to 0.205 ms and conversion +from 3.309 to 2.128 ms. Lower-resolution p95/p99 do not improve uniformly; +monitor pacing and system jitter dominate those cases. Wall-time variation +between runs is not attributed to a wall-ray algorithm change. + +Component means below are **before → after**, milliseconds per presentation. +Capture and snapshot sampling each remain below 0.02 ms in this pair. + +| Internal | Rays/walls | Sprites | RGBA | Upload | Present | +| --- | ---: | ---: | ---: | ---: | ---: | +| 640x480 | 0.5263 → 0.5962 | 0.4463 → 0.1836 | 0.4571 → 0.3735 | 0.2676 → 0.2935 | 0.2090 → 0.2317 | +| 1280x720 | 1.8558 → 2.0028 | 0.4887 → 0.1895 | 1.3352 → 0.9940 | 0.6960 → 0.7275 | 0.2292 → 0.2360 | +| 1920x1080 | 4.6330 → 4.0886 | 0.6235 → 0.2050 | 3.3089 → 2.1275 | 1.2326 → 1.1570 | 0.2391 → 0.2197 | + +For context, Milestone 8's historical X11/VSync-off measurements were: + +| Internal | FPS | p95 ms | p99 ms | CPU % | +| --- | ---: | ---: | ---: | ---: | +| 640x480 | 59.19 | 18.231 | 18.817 | 21.0 | +| 1280x720 | 59.22 | 19.264 | 21.166 | 45.7 | +| 1920x1080 | 57.63 | 21.008 | 24.116 | 76.8 | + +These are the recorded values in `MILESTONE8.md`, not newly rerun numbers. +The paired baseline above is the closer comparison. At the diagnostic 144 FPS +target, Milestone 8 reported 139.06 / 124.64 / 70.90 FPS; the new values are +shown below. Neither experiment establishes physical high-refresh behaviour. + +Additional final X11 controls (same 1280×720 drawable): + +| Control | Internal | FPS | Mean ms | p95 ms | p99 ms | CPU % | +| --- | --- | ---: | ---: | ---: | ---: | ---: | +| VSync on | 640x480 | 59.94 | 16.682 | 17.588 | 17.902 | 17.1 | +| VSync on | 1280x720 | 59.11 | 16.901 | 19.230 | 20.570 | 43.8 | +| VSync on | 1920x1080 | 56.12 | 17.820 | 22.924 | 24.844 | 78.1 | +| 144 target, VSync off | 640x480 | 139.66 | 7.153 | 8.296 | 8.813 | 39.0 | +| 144 target, VSync off | 1280x720 | 133.82 | 7.468 | 9.995 | 11.592 | 81.6 | +| 144 target, VSync off | 1920x1080 | 78.87 | 12.680 | 20.534 | 22.069 | 99.8 | +| Smooth off, VSync off | 640x480 | 178.43 | 5.599 | 9.043 | 10.151 | 26.7 | +| Smooth off, VSync off | 1280x720 | 116.67 | 8.563 | 16.284 | 18.397 | 52.0 | +| Smooth off, VSync off | 1920x1080 | 60.44 | 16.528 | 24.597 | 28.302 | 75.2 | + +The 640×480 VSync control spent 14.153 ms in present and maintained 59.94 FPS, +consistent with no extra monitor-period wait. VSync did not consistently block +at the larger canvases in this compositor; the existing software pacing fallback +remains relevant. Smooth off samples no snapshots and reuses unchanged native +images; its higher present-call count is not a higher gameplay rate. Smooth off +retains the application's existing 4 ms outer wait. No uniform low-latency or +144 FPS guarantee follows from these measurements. + +Dummy video / **SDL software presentation**, Smooth on, VSync off, 60 Hz target: +all regular rows use a 1280×720 output; the last pair has an actual +3840×2160 drawable. This synthetic 4K output is CPU-scaled by SDL, and is +**not a measurement of accelerated 4K monitor presentation**. + +| Internal → output | Version | FPS | Mean ms | p95 ms | p99 ms | CPU % | +| --- | --- | ---: | ---: | ---: | ---: | ---: | +| 640x480 → 1280x720 | Before | 59.34 | 16.835 | 18.177 | 19.151 | 55.6 | +| 640x480 → 1280x720 | After | 59.44 | 16.824 | 18.583 | 19.128 | 53.4 | +| 1280x720 → 1280x720 | Before | 59.43 | 16.810 | 17.620 | 18.554 | 37.5 | +| 1280x720 → 1280x720 | After | 59.49 | 16.809 | 17.725 | 18.136 | 33.7 | +| 1920x1080 → 1280x720 | Before | 55.19 | 18.119 | 19.362 | 19.779 | 99.7 | +| 1920x1080 → 1280x720 | After | 56.24 | 17.782 | 22.284 | 26.845 | 99.4 | +| 1920x1080 → 3840x2160 | Before | 13.40 | 74.612 | 78.031 | 79.960 | 100.1 | +| 1920x1080 → 3840x2160 | After | 13.28 | 75.295 | 80.364 | 90.338 | 100.2 | + +Synthetic 4K software presentation dominates at 62.169 → 63.626 ms per present; +optimising sub-millisecond sprite work cannot remove that backend scaling cost. +This fallback is not smooth on this CPU. Three empty dummy-audio input queues +were observed in the final 4K software run (zero in its baseline); its p99 frame +was 90.338 ms. All other final measurements observed zero empty queues. +Queue emptiness is not a physical underrun measurement, but this is evidence +that sufficiently long blocking software presents can exhaust the existing +80 ms audio queue. No audio latency increase or new producer thread was added +to mask this synthetic backend limit. + +Every measured game-clock increment exactly matched processed deadlines. +The slow 4K software run finished five ticks behind the immediately due clock; +that debt remained outstanding, rather than being discarded. Typical final +60 Hz runs ended zero/one tick behind; the diagnostic 144-target 1080p run ended +two ticks behind. The existing stall and demo tests independently verify debt +retention and deterministic continuation. + +Native X11 requests for 4K windows were clamped to 1918×1127 drawable pixels, +so the harness explicitly excluded those from 4K performance claims. The exact +native capture viewport was 1918×1078; the exact-2× pixel oracle ran under dummy +video instead. A physical accelerated 4K before/after comparison, including the +former native-4K Auto path, remains unperformed. + +Final raw logs are `final-before-native60.log`, `final-after-native60.log`, +`final-after-vsync.log`, `final-before-software.log`, `final-after-software.log`, +`final-after-target144.log` and `final-after-no-smooth.log` in ignored +`build/checks/m9/`. Earlier exploratory `bench-*` logs preceded the final +warmup/drawable checks and are not the numbers reported here. + +## Remaining hardware validation and limits + +The available physical panel is 1920×1200 at SDL-reported 59.880 Hz. A 4K +window/capture and simulated desktop sizes exercise SDL scaling and Auto policy; +they do not constitute testing on a physical 4K panel. No physical 120 Hz or +144 Hz display was available. Diagnostic target overrides measure CPU/present +capacity only. VSync/VRR, compositor behaviour, high DPI, real ultrawide panels, +multiple-monitor migration and live refresh changes still need hardware checks. + +Wine checks API behaviour and portability, not physical Windows presentation. +Dummy audio queue observations do not measure speaker latency or hardware +underruns. Existing main-thread audio buffering tolerates bounded render stalls; +a sufficiently long blocking OS/driver call can still drain it. Real-device +listening/loopback and focus/fullscreen transitions remain acceptance checks. + +The original Classic visibility pass remains authoritative for gameplay; wider +presentation does not change DOS activation/pickup rules. Original ray-angle +quantisation and source-art resolution remain visible. Auto rejects extreme +aspects that cannot fit the renderer's minimum 320×200 target, retaining the +working surface. Manual native targets up to the existing engine limits remain +available to diagnostic harnesses, but Auto never exceeds 1920×1080. No full +campaign playthrough or performance guarantee at 144 FPS is claimed. diff --git a/docs/ORIGINAL_CONTENT_AND_IP.md b/docs/ORIGINAL_CONTENT_AND_IP.md new file mode 100644 index 00000000..0455224f --- /dev/null +++ b/docs/ORIGINAL_CONTENT_AND_IP.md @@ -0,0 +1,26 @@ +# Original game and IP separation specification + +Status: PROPOSAL. This is engineering/licensing planning, not a legal clearance finding. + +## Goal + +Ship an independently recognisable original retro FPS whose installed game does not require Wolfenstein 3D proprietary assets, branding or data. Keep its fast grid-based raycaster and classic-era feel without reproducing protected expressions. + +## Audit required before replacement + +Inventory every source file, dependency, asset, map, name, menu string, UI glyph, font, audio file, weapon/enemy sprite, texture, executable/package identifier, documentation claim, marketing screenshot and third-party tool. Record origin, author, upstream URL or licence text, modification history, distribution rights, replacement disposition and release status. + +Do not assume Wolfenstein source code is public domain or that rebranding discharges any GPL obligations. Source licence compliance, trademarks, proprietary artwork, third-party artwork/audio and original-content provenance are distinct checks. Maintain required copyright notices and original source licence terms. A commercial release may be possible with some open source licensing arrangements, but require a specific audit rather than a blanket assertion. + +## Separation architecture + +- Keep engine/platform responsibilities distinct from game identity/content; derive game resources from data bindings instead of scattered hardcoded identifiers. +- Support a versioned original content pack with manifest, resource IDs, sprites, wall textures, sounds, levels, HUD/menu definitions and game metadata. +- Legacy original-game data, when lawful to test, remains an optional **external** compatibility source and is never quietly bundled in the original distribution. +- Missing/invalid content fails with actionable diagnostics; no silent fallback to uncleared legacy assets. +- Add tests that scan staged release outputs for forbidden names/data and launch original content with legacy directories missing. +- Capture provenance for all new art and sound (created, commissioned, licensed, generated and reviewed), including attribution requirements. + +## R1 revision acceptance + +R1.1 licence/provenance matrix complete; R1.2 references classified; R1.3 engine/content boundary documented and covered; R1.4 legacy isolation regression; R1.5 staged asset manifest and original-only launch definition. Detailed R1 implementation depends on R0 audit. Do not delete legacy files or claim legal release readiness as part of documentation approval. diff --git a/docs/PORTING.md b/docs/PORTING.md new file mode 100644 index 00000000..147ad7bb --- /dev/null +++ b/docs/PORTING.md @@ -0,0 +1,142 @@ +# Source inventory and staged modernisation + +This inventory was recorded during milestone 1, 2026-11-01. The original +`WOLFSRC/` tree remains untouched. Milestone 2 now ports the original title +graphics path with memory, cache/decompression and SDL video support; see +[milestone 2 results](MILESTONE2.md). Milestone 3 adds the original menus, +fonts, input and supported attract flow; see [current results](MILESTONE3.md). +Milestone 4 now implements E1M1 maps/VSWAP, wall tracing, movement and normal +doors; see [milestone 4](MILESTONE4.md). Milestone 5 adds sprites, original +normal-enemy state machines, combat, pickups, HUD and death/life restarts; +see [milestone 5 results](MILESTONE5.md). The first Milestone 6 pass adds +normal-level progression, episode/difficulty selection, secret pushwalls and +intermission scoring; see [current scope and remaining work](MILESTONE6.md). +Milestone 6A now implements remaining bosses/projectiles, BJ/death-camera +victories and original episode statistics/end articles. All 240 owned-map +combinations and controlled SDL finale fights are covered; see +[Milestone 6A](MILESTONE6A.md) for verification and playthrough limits. +Remaining items below are the incremental engine plan, not claims of +completed gameplay. + +## Source-file inventory + +Reviewed the following headers, relevant implementation sections, assembly +exports and the Borland project records. This is a porting inventory, not a +complete behavior audit of every conditional edition. + +| Files inspected (under WOLFSRC/) | Portability issue and intended change | +| --- | --- | +| `ID_HEAD.H`, `ID_HEADS.H`, `WL_DEF.H`, `VERSION.H`, `WOLFVER.H` | Borland uppercase system headers, `SYS\STAT.H`, `ALLOC.H`, `DOS.H`, `MEM.H`, `IO.H`, `VALUES.H`; duplicate types; 16-bit `unsigned`, 32-bit DOS `long`; `far`, `huge`, `_seg`, pragmas. Introduce explicit-width types and ordinary pointers by subsystem, not blanket keyword macros. | +| `ID_MM.C/H`, `ID_PM.C/H` | Paragraph allocation, segment arithmetic, near/far heaps, EMS interrupt 67h, DOS int 21h, XMS int 2Fh and driver calls. Replace with owned heap allocations and bounded VSWAP page buffers while retaining `MM_*` / `PM_*` call sites where practical. | +| `ID_CA.C/H` | DOS file handles and far reads, native structs, 24-bit VGA offsets, Huffman, Carmack and RLEW decoding. Keep decompressor names; use bounded byte readers, explicit little-endian values, checked sizes and errors for truncated streams. | +| `ID_VL.C/H`, `ID_VL_A.ASM`, `ID_VH.C/H`, `ID_VH_A.ASM` | BIOS video calls, VGA ports, A000 framebuffer segments, four planes, latches and page offsets. Translate drawing operations to a 320×200 byte-per-pixel buffer and preserve original palette/fade precision. | +| `WL_DRAW.C`, `WL_DR_A.ASM`, `WL_SCALE.C`, `WL_ASM.ASM` | Inline assembly `FixedByFrac`, `AsmRefresh` ray traversal, segment-addressed textures, generated x86 scaling code/far calls, CPU checks. Translate incrementally to C and compare ray hits, wall heights and pixels before optimization. | +| `ID_IN.C/H` | IRQ1 scan codes/ports 60h, 61h, PIC acknowledgement, int 33h mouse, joystick port 201h. Map SDL physical keys to original set-1 codes, preserve down/up state, relative mouse motion/buttons, clear held state on focus loss. | +| `ID_SD.C/H`, `ID_SD_A.ASM` | PIT/IRQ0 timing, PC speaker ports, AdLib registers, Sound Blaster DMA/interrupts and Sound Source. Separate 70 Hz gameplay from audio service clocks; replace hardware output with PCM and an interchangeable OPL interface. The historical `SDL_*` function prefix here predates Simple DirectMedia Layer. | +| `ID_US_1.C`, `ID_US_A.ASM` | User/UI helpers, native config/save structures, table-based RNG with DOS time seeding. Port the original 256-byte table and index sequence to C, with an explicit deterministic seed for tests. | +| `WL_MAIN.C` | DOS startup/disk queries, config, `SaveTheGame` / `LoadTheGame`, linked palette/signon. Separate startup and path selection; serialize integers explicitly and encode actor/state references as stable IDs. Native pointer dumps are not portable saves. | +| `WL_PLAY.C`, `WL_GAME.C` | `TimeCount` waits, four-tic demos, input sampling, level setup and demo pointer casts. Preserve frame-level tic batching and random call ordering; do not assume one update per rendered frame or replace each batch with independent one-tic updates. | +| `WL_AGENT.C`, `WL_ACT1.C`, `WL_ACT2.C`, `WL_STATE.C` | Player/collision, doors/pushwalls, enemies and state tables. Keep behavior and names; audit integer truncation, signed shifts/overflow, and pointer/sentinel uses in `actorat` before changing types. | +| `WL_MENU.C/H`, `WL_INTER.C`, `WL_TEXT.C` | UI, waits, artwork/text resources and edition branches; retain original flow on the portable drawing/input interfaces. | +| `GFXV_WL6.H`, `AUDIOWL6.H`, `MAPSWL6.H`, `WOLF3D.PRJ`, `README/RELEASE.TXT` | Generated resource indices and historical build dependency records. Medium memory model/TASM, linked object resources, original Borland C++ 3.0 toolchain; generated constants must match the selected data edition. | + +`C0.ASM`, `H_LDIV.ASM` and historical hacks/tools (`DETECT.C`, `MUNGE.C`, +`CONTIGSC.C`, `WOLFHACK.C`, `OLDSCALE.C`, `WHACK_A.ASM`, `JABHACK.ASM`) are +not candidates for indiscriminate inclusion in a modern executable. Audit +their actual required symbols first. Original `OBJ/GAMEPAL.OBJ` and +`OBJ/SIGNON.OBJ` are 16-bit linked resources, not portable SDL assets. Recover +and attribute palette constants separately; do not silently link DOS objects. + +## Compatibility constraints + +`fixed` is originally a 32-bit DOS `long`. `FixedByFrac` multiplies a two's +complement 16.16 coordinate by a signed-magnitude fraction; ordinary signed +16.16 multiplication is not a drop-in replacement. Test signs, zero, cardinal +angles, extrema and truncation against assembly semantics with wide unsigned +intermediates before replacing it. LP64 Linux and LLP64 Windows disagree on +`long`; no disk structure may rely on either native ABI. + +`TickBase` is 70 in `ID_SD.H`; `MAXTICS` is 10 and `DEMOTICS` is 4 in +`ID_HEADS.H`. `CalcTics` clamps long frames and subtracts excess elapsed time. +Preserve that policy, pause resets and demo pacing. Presentation can be +independent, but changing simulation batching can change movement rounding. + +Edition macros include `SPEAR`, `SPEARDEMO`, `UPLOAD`, `GOODTIMES`, `JAPAN`, +`JAPDEMO`, `SPANISH`, `ARTSEXTERN`, `DEMOSEXTERN`, `CARMACIZED`, linked-header +switches and debug/profile switches. The checked-in defaults include +`GOODTIMES`, external art/demos and Carmack compression; they are not proof of +Steam WL6 compatibility. Establish one explicit WL6 profile against the user's +actual files before broadening edition support. Case-sensitive include names +and DOS EOF bytes also need targeted treatment. + +Data-directory support belongs at one file-open boundary, taking +`--data /absolute/path` without changing global working directory. The initial +WL6 set is VSWAP, VGAHEAD/VGADICT/VGAGRAPH, MAPHEAD/GAMEMAPS and +AUDIOHED/AUDIOT. Original code also uses variant names such as MAPTEMP and +extension selection. Validate the whole set and resource indices; recognize +case variants on Linux, reject missing/mixed editions, and never infer success +from file existence alone. Original DOS-save import and portable-save output +must be explicit, separate format decisions. + +## Platform boundary design + +Keep original `ID_*`/`WL_*` ownership and names as files are ported. New SDL +implementation files will live separately under `src/platform/`; do not add +SDL headers to actor or raycasting logic. Move a module into the active build +only once its dependency slice compiles and has meaningful checks. Preserve +history with moves rather than replacing the tree with a reference project. + +The video boundary accepts indexed pixels, stride and a 256-entry palette. +The SDL_Renderer backend owns window/renderer/streaming RGB texture, palette +expansion, nearest filtering, centered 4:3 viewport/letterboxing, resize and +fullscreen. This deliberately corrects VGA pixel aspect: stretching 320×200 +into 4:3 differs from square-pixel 8:5. Keep palette-only updates visible. +The same boundary can later support SDL_GPU without changing game logic. + +Input exports set-1 key events/states and relative mouse deltas/buttons. Timing +supplies monotonic counters and sleep; tests inject virtual time. Audio owns +SDL PCM buffering; an OPL adapter accepts timestamped register writes and +generates samples. Silence must still advance sequencing. No audio clocks +should derive from presentation frequency. No platform API is implemented +beyond the original UI slice in milestone 3. Monotonic timing and keyboard +input, gameplay and native shared-OPL/SDL3 audio are now implemented; see +[MILESTONE6B.md](MILESTONE6B.md) for the actual audio boundary and limitations. + +## Reference findings + +Reviewed [wolf3d-lib architecture](https://github.com/bobapplemac/wolf3d-lib/blob/main/docs/architecture.md), +[porting guide](https://github.com/bobapplemac/wolf3d-lib/blob/main/docs/porting-guide.md), +`src/WG_FIXED.c`, source/test layout and licensing inventory. Useful patterns +are bounded little-endian resource parsing, indexed framebuffer ownership, +host callbacks, a headless test host and preserved live/demo tic batching. +Its C99 conversion is a reference for our C11 work, not a replacement core. + +Reviewed [wolf3d-portable's SDL3 host](https://github.com/bobapplemac/wolf3d-portable/blob/main/platforms/sdl3/WG_SDL3.c), +README, layout and third-party notices. It maps SDL scancodes to set-1 keys, +uses a streaming RGBA texture with nearest sampling and logical presentation, +and supplies PCM through an SDL audio stream. These demonstrate the proposed +separation; no implementation was copied. For audio, the library guide keeps +700 Hz IMF and 140 Hz effects independent of the game clock and negotiates +the application PCM rate. Follow that separation when restoring `ID_SD`. + +## Small reviewable milestones + +1. **Prepared here:** Git safeguards, inventory, C11 type baseline, CART/SDL3 + dependency probe. Original game is not yet compilable. +2. **Portable-core slices:** milestone 2 ports the 149-chunk WL6 title path, + memory manager, bounded graphics decompression and indexed video. Next port + `US_RndT` and fixed-point helpers with oracle vectors, then CA map-plane + and PM VSWAP decoding against synthetic malformed streams and owned data. + Data path selection is implemented for the title. Progress toward a playable core + subsystem by subsystem; avoid a mass header rewrite. +3. **Video:** title presentation, original palette, resize, nearest scaling and + buffer tests are implemented. Milestone 3 adds original UI primitives, fonts, + ordinary pictures, menus and fades. Fullscreen remains later work. +4. **Input/gameplay:** integrate IN/timing and restore player, doors, weapons, + enemies and demos; compare deterministic traces and original tic batching. +5. **Audio:** SDL PCM, original digitized samples and sequences, then reviewed + OPL integration with independent rational sample clocks. +6. **Compatibility:** original WL6 map start/playthrough, secrets, doors, + enemies, save/load and demo comparisons using external owned data. +7. **Enhancements only after parity:** optional widescreen/high refresh, + gamepad, settings and SDL_GPU. Keep original gameplay as the default. diff --git a/docs/WINDOW_ASPECT_FIX.md b/docs/WINDOW_ASPECT_FIX.md new file mode 100644 index 00000000..63573d69 --- /dev/null +++ b/docs/WINDOW_ASPECT_FIX.md @@ -0,0 +1,130 @@ +# Independent window, DOS menu and gameplay aspects + +**Branch:** `fix/window-aspect-independent-controls` + +The SDL window stays at the user's chosen dimensions. Entering or leaving +menus changes only the rendered presentation. + +## Behaviour + +- DOS menus, startup pages and static game screens retain the original + 320x200 indexed framebuffer. Presenting that image on a centred 320x240 + logical canvas corrects DOS pixel aspect to 4:3. Unused output is black. + Artwork, fonts, buttons and the pistol cursor stay together in that image. +- Menu scaling selects Fit or Integer. Tiny windows fall back to Fit rather + than cropping. Enhanced gameplay always fits its selected aspect into the + available output, independently of integer menu scaling. +- Gameplay aspect selects Auto, 4:3, 16:9, 16:10, 21:9 or 32:9. Auto uses + drawable pixels (including DPI scaling), within the existing 4:3–32:9 range. + Aspect choices do not resize the window or select an internal resolution. +- Display settings opens directly from the classic Control screen. The + Customize controls route remains available. Escape returns to the Control + page from which Display was opened. Arrow keys and Enter navigate settings. +- Display labels distinguish Fullscreen, Menu scaling, Window size, 3D + renderer, Internal 3D size, Gameplay aspect, VSync, Texture filter and Smooth + rendering. The internal Auto option retains its existing desktop-derived + 1920x1080 ceiling; it does not select the SDL window size. + +Window size cycles in either direction, wrapping through these presets: + +| Aspect | Window dimensions (SDL window points) | +| --- | --- | +| 4:3 | 640x480, 960x720, 1280x960 | +| 16:10 | 960x600, 1280x800, 1600x1000, 1920x1200 | +| 16:9 | 960x540, 1280x720, 1600x900, 1920x1080 | +| Ultrawide | 1680x720, 2560x1080, 1920x540, 2560x720 | + +Arbitrary dimensions set by the window manager remain supported. From an +unlisted size, Right selects the first preset and Left selects the last. +Preferences save explicit width and height separately from rendering settings. +Fullscreen retains the windowed dimensions and restores them on exit; changing +Window size while fullscreen selects the dimensions for the next windowed view. + +The existing asynchronous SDL request handling remains authoritative. A +rejected operation rolls back its settings. A request not applied within three +seconds reports an error, releases the pending state and adopts the actual +windowed size. Window-manager limits can therefore reduce a requested preset; +the preset list does not promise every size fits the current monitor. Minimized, +maximized and fullscreen dimensions do not replace the remembered normal size. + +## Review and changes + +The existing implementation was reviewed against `master`, including +`WL_DISPLAY.c`, `WL_CONTROLS_MENU.c`, `sdl_video.c`, `WL_MAIN.c`, preference +persistence and the display/DOS menu tests. It was extended rather than replaced. + +- `WL_CONTROLS_MENU.c`: direct Display entry with original menu artwork, + font, colours and cursor styling; updated DOS composition oracle. +- `WL_DISPLAY.c`: independent window presets, selection reset on opening and + clearer labels that fit the original font layout. +- `sdl_video.c`: exclude enhanced world presentation from integer menu scaling. + Previously this setting could leave enhanced gameplay unnecessarily small. +- `display_tests.c` / `test_display.py`: all 15 presets in both directions, + wrapping and arbitrary-size recovery; fit/integer geometry and black-border + readback; explicit aspects and Auto; resize-event and dimension assertions + across game → menu → Control → Display → Control → menu → game; fullscreen + restoration and manual resizing. The old 4:3-only test expectation was fixed. +- `test_config.py`: save/restart restoration of every preset and an arbitrary + size, retaining independent gameplay aspect and menu scaling preferences. + +No simulation, demo decoding, HUD rendering or Milestone 9 performance +optimisation code was changed. `WL_MAIN.c` already restores the correct Control +page after Display; no additional transition code was necessary. + +## Validation + +Checks used GCC 14.2 with strict C11, `-Wall -Wextra -Wpedantic +-Wconversion -Wshadow -Werror`. Linux builds used the local SDL3 3.5.0 +development SDK; MinGW used SDL3 3.4.18. + +| Check | Result | +| --- | --- | +| Strict Linux application and SDL test build | Passed | +| CART `cart-sdl` build | Passed | +| Strict MinGW application and SDL display test build | Passed | +| Windows display tests under Wine, owned WL6, dummy/software SDL | Passed: presets, navigation, gameplay isolation and aspect transitions | +| Full Python test suite with owned WL6 data | Passed: 126 tests, no skips (626.324 s) | +| Full ASan/UBSan suite with owned WL6 data | Passed: 126 tests across 12 modules, no skips or findings (588.040 s) | +| Native X11/OpenGL presentation and transition checks | Passed, subject to the limits below | + +The full suites include original DOS demo traces (all four demos, 5386 commands, +classic and enhanced rendering), DOS menu pixel comparisons, native rendering +hashes, control binding conflicts, deterministic save/load and audio isolation. +Sanitizer test modules run in four independent subprocesses with +`SANITIZE=1`, `CC='gcc -O1'` and `UBSAN_OPTIONS=halt_on_error=1`; the application +binary also uses AddressSanitizer and UndefinedBehaviorSanitizer. Each module's +exit status and sanitizer output are checked. + +The normal suite can be reproduced after building the application: + +```sh +WOLF3D_BINARY="$PWD/build/checks/window-aspect/wolf3d-revive" \ +WOLF3D_DATA="/path/to/owned/WL6" CC='gcc -O1' \ +python3 -m unittest discover -s tests -v +``` + +`tests/display_tests.c` also accepts the `transitions` mode with a data directory +and writable save directory to exercise native SDL window transitions. The +Python runner selects dummy/software SDL for reproducible exact preset sizes. + +### Native display and limits + +Linux SDL3 X11/OpenGL checks ran on a physical 1920x1200 panel at approximately +60 Hz. For Control, Display, intermission, victory and end-text captures, every +output pixel matched the original indexed framebuffer enlarged with 5x6 texels, +with 160-pixel black borders on each side. Display label widths were checked +against the value column and the captured layout was visually inspected. + +Native transition checks passed for 960x720, 960x540, 960x600, 1680x720 and +1001x601, with explicit gameplay aspects and Auto. They observed zero SDL window +resize events during menu/game transitions, retained integer menu scaling, +restored fullscreen/windowed sizes and adopted manual window resizes. +A 2560x720 request was clamped to 1918x720 by the window manager; the timeout +path reported the limit and adopted that size. The same transition checks then +passed at the actual size. + +Physical 32:9, high-DPI/mixed-DPI, multi-monitor and native Windows display +validation were unavailable. Exact large sizes and 32:9 are covered by SDL's +software/dummy backend; Wine checks do not establish native Windows display +behaviour. No claim is made that oversized windows fit this panel. Commercial +game data and captures remain external or in ignored `build/checks` paths. diff --git a/docs/WORKSHOP_DESIGN.md b/docs/WORKSHOP_DESIGN.md new file mode 100644 index 00000000..f0134989 --- /dev/null +++ b/docs/WORKSHOP_DESIGN.md @@ -0,0 +1,32 @@ +# Workshop: first-person grid authoring proposal + +Status: PROPOSAL. Simple walk-around building, not CAD, not Ironclaw3D's structural/freeform 3D system. + +## Product experience + +Enter Workshop from game UI. Walk using normal game movement. Aim at a tile/edge, see a clearly coloured valid/invalid preview, click/place or delete. Choose a simple palette: wall, door, floor/wall appearance, decorations, player start, enemy, item and secret. A wall drag creates a whole straight run; a room rectangle creates perimeter walls with a valid interior. Every object snaps to the game's tile grid. No flying, separate top-down CAD tool, freeform mesh sculpting or complex material node interface in v1. + +Create -> edit -> save -> playtest -> return -> continue editing. Hot-loading means changes are applied at a safe game/editor boundary or explicitly rebuilt only where needed; no unsafe live mutation during active simulation frames. + +## One shared model and API + +The same validated world representation and content IDs drive game simulation, renderer, save/load and Workshop UI. Native C operations, independent of SDL input/rendering, should include concepts such as `world_new`, `world_validate`, `world_set_tile`, `world_place_object`, `world_remove_object`, `world_begin_edit`, `world_commit_edit`, `world_undo`, `world_redo`, `world_save` and `world_load`. These are illustrative **proposed API names**, not implemented symbols or ABI promises. + +Avoid global editor-only world state. Define object identity and ownership, mutation atomicity, deterministic operation order, versioned formats, error codes and asset resolution. The editor can be temporarily paused for playtest; the authored world is durable and game-session transient state is separate. + +## Constraints + +- Respect current grid, wall collision and raycasting constraints; do not introduce multi-storey blocks or unconstrained heights merely for editing. +- Mouse/keyboard first. Controller/Android touch editing can be a separate later design with confirmed need. +- Clear affordances: highlight active tool, readable preview, snap target and invalid placement reason; undo is essential before extensive content authoring. +- Validate occupied tiles, doors, spawn reachability, map edges, duplicates, resource limits and unknown IDs. +- Save/load must produce the same semantic map; version migrations must be explicit and tested. +- Workshop is optional to playing the shipped original game. + +## Delivery slices + +R4 headless edit and transaction semantics -> R5 in-world selection, placement, line/room tools and objects -> R6 atomic persistence, hot-load and return loop -> R7 full gameplay placement, undo UI and new-player usability -> R8 distribution. + +## First proving demo + +Using original placeholder art, create a small square room, add a corridor and door, place a start and an enemy, save to disk, restart, play it, then return to Workshop and edit a wall. Record deterministic API test, screenshot capture in Classic and Enhanced, invalid-placement cases and an observed hands-on session. Only then broaden the palette. diff --git a/docs/automation/PLAYBOOK.md b/docs/automation/PLAYBOOK.md new file mode 100644 index 00000000..f9687b20 --- /dev/null +++ b/docs/automation/PLAYBOOK.md @@ -0,0 +1,334 @@ +# Reusable workflow playbook and automation backlog + +Status: PROPOSAL / WORKFLOW SPECIFICATION. This file is long-lived operational knowledge for Codex and Gemma, not a replacement for source inspection. + +## Rule: solve once, reuse across agents + +Whenever a procedure requires repeated investigation, repeated commands or repeated manual validation: +1. Search this playbook, `tools/`, `tests/` and existing Rn.m validation reports first. +2. Identify stable inputs, outputs, preconditions, failure conditions and side effects. +3. Implement/extend a **single canonical script** for recurring deterministic work, with unit or smoke tests. For non-automatable actions, maintain one precise repeatable checklist. +4. Record command, owner, parameters, dependencies, expected exit codes, evidence output and platform limitations here. +5. Invoke that workflow in subsequent milestone acceptance criteria; do not ask another agent to rediscover it. +6. If a task cannot safely be automated, capture why and keep a documented manual gate. + +A second occurrence triggers an automation candidate. Tasks with high risk or likely repeated use can be prioritised immediately. Do not add complicated orchestration for a one-off task. + +## Canonical automation candidates + +| ID | Repeated work | Proposed canonical interface | Planned milestone | Status | +| --- | --- | --- | --- | --- | +| AUTO-01 | Build/smoke environment checks | `tools/doctor.sh` | R0.1/R0.6 | R0.1 PROCEDURE DOCUMENTED; SCRIPT NOT IMPLEMENTED | +| AUTO-02 | Fast headless/unit regressions | `tools/test.sh` | R0.3/R0.6 | IMPLEMENTED (thin wrapper to tools/validation/run.py) | +| AUTO-03 | SDL graphics/display regression | `tools/test.sh --graphics` | R0.4/R0.6 | IMPLEMENTED (R0.4 graphics jobs selected via runner) | +| AUTO-04 | ASan/UBSan test matrix | `SANITIZE=1 tools/test.sh` | R0.5/R0.6 | R0.5 REPRESENTATIVE EVIDENCE RECORDED; WRAPPER NOT IMPLEMENTED | +| AUTO-05 | Revision-based gating and progress/logs | `python3 tools/validation/run.py R0.4` | R0.6 | IMPLEMENTED (milestone selection, logs, JSON summary, bounded timeouts) | +| AUTO-06 | Deterministic capture comparison | `python3 -m unittest discover -s tests -p test_render.py -v` | R0.4 | IMPLEMENTED IN EXISTING RENDER UNITTEST DRIVER | +| AUTO-07 | Content provenance and banned-asset scanning | `tools/audit_content.py` (interface subject to design) | R1 | NOT IMPLEMENTED | +| AUTO-08 | Map/content fixture validation | `tools/validate_content.py` (interface subject to design) | R2 | NOT IMPLEMENTED | +| AUTO-09 | Workshop round-trip integration | revision-selected test fixture | R6.6 | NOT IMPLEMENTED | +| AUTO-10 | PR evidence/checklist creation | CI/template based on real test metadata | R0.6 | PARTIAL (CI workflow added; real-run confirmation pending) | +| AUTO-11 | Texture/resource dimension inventory | extend future `tools/audit_content.py` with bounded metadata-only inspection | R1/R2 | R0.1 ONE-OFF INVENTORY ONLY; NOT IMPLEMENTED | + +The table is a **backlog**; no script is claimed to exist. Replace speculative names with tested stable commands when each revision delivers. + +## Verified R0.1 procedures + +These commands were inspected and executed on 22 November 2026. Full results, +limitations and tool versions are in [`docs/milestones/R0/R0.1.md`](../milestones/R0/R0.1.md). +They remain valid low-level commands. R0.6 also provides `tools/test.sh` and `tools/validation/run.py` as the canonical validation surface; see "Verified R0.6 validation command surface". + +Prerequisites: + +- CART 0.2.0 available as `build/tools/cart` (ignored) or by an explicit path. +- a built SDL3 tree at `../cart/vendor/SDL` for profile `cart-sdl`. +- GCC and Python 3; owned-data checks additionally require a legal external + WL6 directory supplied through `WOLF3D_DATA` or `--data`. +- no dependency installer or game-data downloader is invoked by these commands. + +Configured optimized build: + +```sh +./build/tools/cart build --profile cart-sdl --verbose +``` + +CART's desktop `build` command has no named debug/release mode. The profile +build currently receives CART's `-O0 -g` followed by project `-O2`; GCC applies +the final optimization option. A strict debug compile of the same source set is: + +```sh +gcc -std=c11 -O0 -g3 \ + -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror \ + -Isrc -I../cart/vendor/SDL/include \ + src/main.c src/engine/*.c src/platform/*.c \ + ../cart/vendor/SDL/build/libSDL3.a -pthread -lm \ + -o build/wolf3d-revive-debug +``` + +`cart doctor` does not accept profiles. In the current layout its base check +correctly reports missing ignored `vendor/SDL`; verify the sibling profile +prerequisites explicitly until AUTO-01 is implemented. For a clean-checkout +gate, invoke a known CART executable by absolute path from a detached clean +worktree; do not run `cart clean` in the primary checkout because `build/` also +contains the ignored CART executable. + +Finite validation and smoke commands: + +```sh +build/cart-sdl/linux/wolf3d-revive --data /absolute/path/to/WL6 --check-assets +build/cart-sdl/linux/wolf3d-revive --data /absolute/path/to/WL6 --check-ui +build/cart-sdl/linux/wolf3d-revive --data /absolute/path/to/WL6 --check-level + +SDL_VIDEODRIVER=dummy SDL_RENDER_DRIVER=software SDL_AUDIODRIVER=dummy \ + XDG_DATA_HOME="$PWD/build/validation/smoke-user" \ + build/cart-sdl/linux/wolf3d-revive \ + --data /absolute/path/to/WL6 --level --no-audio --frames 3 +``` + +Existing full regression: + +```sh +python3 -m unittest discover -s tests -v +WOLF3D_DATA=/absolute/path/to/WL6 python3 -m unittest discover -s tests -v +``` + +The first form is redistributable/synthetic coverage. The second enables the +private compatibility checks and must never stage the input data or generated +captures. In R0.1 the owned-data form ran 153 tests with no skips and exit 0. +The suite already exercises both Classic and Enhanced SDL paths, but it does +not replace the planned R0.4 capture/human-review gate or R0.5 sanitizer gate. + +## Architecture inspection procedure + +R0.1 and R0.2 both required the same source-boundary inventory. Until a +reviewed helper exists, use this deterministic, read-only procedure from the +repository root and save its output in the revision evidence directory: + +```sh +mkdir -p build/validation/R0.2 + +{ + git rev-parse HEAD + find src -type f \( -name '*.c' -o -name '*.h' \) -print | sort + rg -n '^#include[[:space:]]+[<"]' src + rg -n '#include[[:space:]]+ build/validation/R0.2/architecture-inspection.log +``` + +Replace `R0.2` with the selected revision. `ctags` must be available and its +implementation/version should be noted when output format matters. The scan +finds dependency and global-state candidates; it does not prove call direction +or ownership. Trace startup, shutdown, allocation, mutation and borrowed +pointer lifetime in the implementation before recording an architecture edge. +For Mermaid diagrams, review every arrow against that trace and check code +fences are balanced. Do not infer purity from a function name: R0.2 found +Classic rendering also mutates visibility/activation bookkeeping. + +**Automation candidate AUTO-12:** add a small architecture inventory command +after R0.3 establishes test helpers. It should emit sorted direct includes, +SDL include violations outside the approved platform/main allow-list, and a +curated global-state reference inventory. It must not attempt to infer semantic +ownership. Add golden/failure tests and extend this canonical procedure rather +than creating revision-specific scan scripts. + +Store repeatable revision evidence under ignored +`build/validation//`. Record each command and exit separately; a +successful compile is not a test result. Until R0.6, callers must supply their +own bounded timeout and preserve complete stdout/stderr. + +## Verified R0.4 graphics baseline + +The synthetic Classic/Enhanced baseline is part of the existing render +unittest driver; no proprietary game data or external image package is needed: + +```sh +python3 -m unittest discover -s tests -p test_render.py -v +``` + +The command compiles the established C render harness, constructs the existing +synthetic archives, generates all canonical indexed captures in a temporary +directory, verifies the archive/manifest capture ID set, checks every archived +capture's dimensions and SHA-256, and then compares candidate dimensions, +metadata, hashes and exact pixels with `tests/fixtures/visual_baselines.json` +and `tests/fixtures/visual_baselines.zip`. Candidate hash equality never skips +archive validation. It exits nonzero on a mismatch, including a missing archive +entry or corrupted archived pixels. Owned-data compatibility cases remain skips +when `WOLF3D_DATA` is absent; the synthetic baseline itself is required and +cannot skip. + +To retain palette-correct BMPs and a run manifest for manual inspection: + +```sh +WOLF3D_BASELINE_DIR="$PWD/build/validation/R0.4/captures" \ + python3 -m unittest discover -s tests -p test_render.py -v +``` + +This writes generated `.w3i`, `.bmp` and `manifest.json` files below the ignored +build directory. Review Classic corrected 4:3 at 640x480, letterboxed 1280x720 +and non-integer 1001x601; then review Enhanced 4:3, 16:9, 16:10, 21:9, 32:9 +and Auto. Check corridor depth and sprites, the three door and pushwall states, +viewport-edge clipping, HUD/weapon placement, black bars and restored display +images. Record the reviewer, platform/backend, date and each result separately; +capture generation is not human approval. + +Baseline replacement is a review operation, not a normal validation step. +After an intentional renderer change, set `WOLF3D_UPDATE_BASELINES=1` only in a +reviewed working tree, inspect the resulting manifest/archive diff and retained +BMPs, and run the ordinary command again without that variable. Never update a +baseline merely to make an unexplained failure pass. + + +## Verified R0.5 sanitizer and performance baseline + +R0.5 evidence is recorded in [`docs/milestones/R0/R0.5.md`](../milestones/R0/R0.5.md). +Raw logs are kept under ignored `build/validation/R0.5/logs/`. + +### Sanitizer runs (representative synthetic scope) + +Prerequisites: GCC with libasan/libubsan (validated with GCC 14.2.0), SDL3 +static build at `../cart/vendor/SDL/build/libSDL3.a`, Python 3. Existing test +wrappers add `-fsanitize=address,undefined -fno-omit-frame-pointer` when +`SANITIZE=1`. + +Representative bounded commands (run from repository root; capture stdout/stderr +and exit code): + +```sh +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_engine.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_render.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_classic.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_display.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_presentation.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_save.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_config.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_controls.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_loading.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_audio.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_signon.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_dos_menus.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_dos_ui_reference.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_demo_sync.py -v +``` + +Coverage caveat: suites compile instrumented C harness binaries when +`SANITIZE=1` is set, but `test_engine.py`, `test_config.py`, and +`test_signon.py` may also invoke the prebuilt `WOLF3D_BINARY` for some cases; +those app subprocesses are not ASan/UBSan-instrumented unless rebuilt with +sanitizers. Do not claim app-subprocess coverage as sanitized. + +After runs, scan logs for `AddressSanitizer`, `UndefinedBehaviorSanitizer`, +`LeakSanitizer`, `runtime error:`, and `SUMMARY:`. Any application-owned +finding is A15-blocking until resolved or explicitly documented with owner. + +### Synthetic performance baseline + +`tests/synthetic_perf_benchmark.c` measures CPU renderer frame-time distributions +for deterministic empty/populated synthetic scenes. With `-DWOLF3D_BENCHMARK`, +it also records SDL `frame_total` (`GameDrawPaused()+VW_UpdateScreen()`) and +separates WL_PROFILE `sdl_convert`/`sdl_upload`/`sdl_present` phases under SDL +dummy/software. Fixed render dimensions are selected with `render_auto=false` +and verified via `VL_DisplayGet()` after `VL_DisplaySet()`. + +Reproducible workflow: + +```sh +python3 tools/r0_5_synthetic_perf.py --timeout 600 +``` + +The script generates synthetic data via `tests/game_fixtures.py`, compiles +CPU-only and SDL-profile benchmark binaries, runs them, and writes logs/CSV/ +summary under `build/validation/R0.5/`. It requires no owned WL6 data and no +network. Do not invent target FPS pass/fail criteria. + + +## Verified R0.6 validation command surface + +Evidence: [`docs/milestones/R0/R0.6.md`](../milestones/R0/R0.6.md). Logs/JSON +under ignored `build/validation///`. + +### Commands + +```sh +python3 tools/validation/run.py R0.3 +python3 tools/validation/run.py R0.4 +python3 tools/validation/run.py R0.5 +python3 tools/validation/run.py R0.6 +python3 tools/validation/run.py all +python3 tools/validation/run.py R0.6 --list +python3 tools/validation/run.py R0.6 --dry-run + +tools/test.sh +tools/test.sh --graphics +tools/test.sh --sanitizer +tools/test.sh --performance +tools/test.sh --all +``` + +### Behaviour + +- Each job prints START, timeout, command; ends PASS/FAIL/TIMEOUT/SKIP/NOT RUN + with exit code and duration. +- Jobs run in new process groups; timeout kills the group (TERM then KILL). +- Mandatory job failure/timeout/NOT RUN causes overall nonzero exit. +- `WOLF3D_UPDATE_BASELINES` is stripped from job environments. +- JSON summary: `build/validation///summary.json` (schema v1). +- CI workflow `.github/workflows/validation.yml` runs R0.6 mandatory synthetic + tests on push to `docs/revival-roadmap-and-validation` and PRs targeting + `master`; sanitizer/perf/owned-data/GPU are not default CI gates. CI pass is + not claimed until a real workflow run confirms it. + +## Required script contract + +- Compatible with the target toolchain; avoid unnecessary new dependencies. +- `--help` or documented usage, failure on invalid arguments and missing prerequisites. +- Clear `START`, `PASS`, `FAIL`, `SKIP/NOT RUN` lines and an unmistakable final summary. +- Non-zero exit when any required stage fails; never swallow underlying failures. +- Bounded execution with per-stage timeout and progress markers so a long sanitizer suite cannot silently hang. +- Separate fast CPU tests from optional/required graphics, platform and longer-running jobs. +- Preserve stdout/stderr logs and metadata under `build/validation//` (or documented equivalent). +- No network installation, hidden environment mutation or destructive cleanup by default. +- Prefer idempotent operations; if not idempotent, document backups, output overwrite behaviour and recovery. +- Include tests for the script's failure path, timeout, argument parsing and exit propagation. + +## Evidence and state handoff + +A revision report should contain: + +```text +Revision: Rn.m +Status: PASS | FAIL | PARTIAL | NOT RUN +Branch / commit: +Host / OS / compiler / SDL: +Changes: +Commands executed (real, not proposed): +Outputs / exit codes / log paths: +Acceptance matrix: +Performance / captured image evidence: +Open defects and exact reproduction: +Next action and next command: +Reusable procedure added or updated: +``` + +A failed gate remains failed even if another agent is expected to fix it. Reference logs and PR numbers so the next agent can resume without starting over. + +## Revision process template + +1. Read `AGENTS.md`, `docs/plan.md` and this playbook. +2. Select the next unclosed Rn.m contract and confirm prerequisites. +3. Check existing scripts before introducing a tool. +4. Make a narrowly scoped change on a branch. +5. Run focused validation then mandated regression; log real results. +6. Improve the shared command/playbook if this work is or will be repeated. +7. Attach acceptance evidence; request review. +8. Resolve review findings and rerun necessary gates before merge. +9. Record next step and current blockers for agent handoff. + +## Safety and scope of automation + +CI can run checks and post summaries once approved. Automatic fixes, PR merges, deletion of branches, uploads or publishing are distinct opt-in privileges and must not be implied by this plan. Never store credentials, tokens, private artifacts or protected game assets in scripts/logs. Human visual reviews, fresh-player usability, legal licence decisions and release sign-off remain manual gates even if supported by automated evidence. + +## Reference + +Ironclaw3D `tools/test.sh` and M3/M10 validation reports demonstrate the discipline: actual commands, explicit failures, reproducible captures, metrics and open acceptance gates. Adapt to Wolf3D's existing SDL renderer and fixed-tick semantics rather than copying Ironclaw-specific code. diff --git a/docs/dos_state_transitions.json b/docs/dos_state_transitions.json new file mode 100644 index 00000000..7e14f39e --- /dev/null +++ b/docs/dos_state_transitions.json @@ -0,0 +1,3998 @@ +{ + "schema": 1, + "introduction": [ + "Scope: registered GOODTIMES WL6 historical source and native SDL3 engine. This is a reviewed directed-route inventory, not an exhaustive enumeration of every branch/input combination.", + "Evidence records distinguish source review, native regression assertions and execution of the checksum-verified original DOS executable. Current run results are in [Milestone 13](MILESTONE13_FINAL_FIDELITY.md)." + ], + "states": [ + "article", + "attract-scores", + "boss", + "boss-replay", + "completion", + "controls", + "credits", + "death-ack", + "death-turn", + "demo", + "difficulty", + "disk", + "display", + "end-confirm", + "episode", + "error", + "exit", + "gameplay", + "jukebox", + "load", + "menu", + "message", + "name-entry", + "pause", + "process", + "psyched", + "qualification", + "quick-confirm", + "quick-disk", + "quit-confirm", + "rating", + "red-fizzle", + "replace-confirm", + "restart", + "results", + "reveal", + "save", + "scores", + "secret-completion", + "setup", + "signon", + "sound", + "title", + "victory", + "view", + "warp" + ], + "transitions": [ + { + "id": "startup", + "group": "Startup", + "from": "process", + "to": "signon", + "trigger": "Initialize subsystems and optional SIGNON.RAW", + "source": [ + "WOLFSRC/WL_MAIN.C:InitGame", + "WOLFSRC/WL_MENU.C:IntroScreen" + ], + "implementation": [ + "src/engine/WL_MAIN.c:DemoLoopStartupDevices", + "src/engine/WL_MAIN.c:DemoLoopSignon" + ], + "artwork": "Owned 320\u00d7200 sign-on; actual mouse/audio capability lights.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Native initialization; optional sign-on 10-tic fade.", + "sound": "Silent sign-on.", + "input": "Fresh key acknowledges; M enters jukebox.", + "evidence": [ + "signon" + ], + "status": "partial", + "gaps": [ + "hardware", + "presentation" + ] + }, + { + "id": "signon-ack", + "group": "Startup", + "from": "signon", + "to": "rating", + "trigger": "FinishSignon acknowledgement", + "source": [ + "WOLFSRC/WL_MAIN.C:FinishSignon", + "WOLFSRC/WL_INTER.C:PG13" + ], + "implementation": [ + "src/engine/WL_MAIN.c:SignonPrompt", + "src/engine/WL_MAIN.c:DemoLoopIntro" + ], + "artwork": "Original Working prompt then PG13 at (216,110).", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic black fade with original gamepal reveal; simulation frozen.", + "sound": "Title music 7 begins on rating/title boundary.", + "input": "Clear acknowledging input.", + "evidence": [ + "signon" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "rating-title", + "group": "Attract", + "from": "rating", + "to": "title", + "trigger": "Seven seconds or fresh input", + "source": [ + "WOLFSRC/WL_INTER.C:PG13", + "WOLFSRC/WL_MAIN.C:DemoLoop" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "PG13 to TITLEPIC.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "7\u00d770-tic hold, 30-tic black fade.", + "sound": "Track 7.", + "input": "Fresh input skips rating.", + "evidence": [ + "signon" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "title-credits", + "group": "Attract", + "from": "title", + "to": "credits", + "trigger": "Attract deadline", + "source": [ + "WOLFSRC/WL_MAIN.C:DemoLoop", + "WOLFSRC/WL_GAME.C:PlayDemo" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ChangeScreen", + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "TITLEPIC \u2192 CREDITSPIC", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "15\u00d770 tics plus 30-tic black fades.", + "sound": "Title/score/level tracks selected at boundaries.", + "input": "Any fresh key/click opens menu.", + "evidence": [ + "demo" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "credits-scores", + "group": "Attract", + "from": "credits", + "to": "attract-scores", + "trigger": "Attract deadline", + "source": [ + "WOLFSRC/WL_MAIN.C:DemoLoop", + "WOLFSRC/WL_GAME.C:PlayDemo" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ChangeScreen", + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "CREDITSPIC \u2192 HIGHSCORESPIC", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10\u00d770 tics plus 30-tic black fades.", + "sound": "Title/score/level tracks selected at boundaries.", + "input": "Any fresh key/click opens menu.", + "evidence": [ + "demo" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "scores-demo", + "group": "Attract", + "from": "attract-scores", + "to": "demo", + "trigger": "Attract deadline", + "source": [ + "WOLFSRC/WL_MAIN.C:DemoLoop", + "WOLFSRC/WL_GAME.C:PlayDemo" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ChangeScreen", + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Scores \u2192 original demo overlay", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10\u00d770 tics plus 30-tic black fades.", + "sound": "Title/score/level tracks selected at boundaries.", + "input": "Any fresh key/click opens menu.", + "evidence": [ + "demo" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "demo-title", + "group": "Attract", + "from": "demo", + "to": "title", + "trigger": "Demo ends/dies/exits or cannot start", + "source": [ + "WOLFSRC/WL_GAME.C:PlayDemo", + "WOLFSRC/WL_MAIN.C:DemoLoop" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Game \u2192 TITLEPIC.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic black fade with original gamepal reveal; simulation frozen.", + "sound": "Stop level music; title music.", + "input": "Demo commands isolated from live bindings.", + "evidence": [ + "demo" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "title-menu", + "group": "Attract", + "from": "title", + "to": "menu", + "trigger": "Fresh key or mouse", + "source": [ + "WOLFSRC/WL_MAIN.C:DemoLoop", + "WOLFSRC/WL_MENU.C:US_ControlPanel" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Original control-panel artwork.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic black fade with original gamepal reveal; simulation frozen.", + "sound": "Menu track 14.", + "input": "Abort demo and release its game resources.", + "evidence": [ + "classic", + "demo" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "credits-menu", + "group": "Attract", + "from": "credits", + "to": "menu", + "trigger": "Fresh key or mouse", + "source": [ + "WOLFSRC/WL_MAIN.C:DemoLoop", + "WOLFSRC/WL_MENU.C:US_ControlPanel" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Original control-panel artwork.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic black fade with original gamepal reveal; simulation frozen.", + "sound": "Menu track 14.", + "input": "Abort demo and release its game resources.", + "evidence": [ + "classic", + "demo" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "attract-scores-menu", + "group": "Attract", + "from": "attract-scores", + "to": "menu", + "trigger": "Fresh key or mouse", + "source": [ + "WOLFSRC/WL_MAIN.C:DemoLoop", + "WOLFSRC/WL_MENU.C:US_ControlPanel" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Original control-panel artwork.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic black fade with original gamepal reveal; simulation frozen.", + "sound": "Menu track 14.", + "input": "Abort demo and release its game resources.", + "evidence": [ + "classic", + "demo" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "demo-menu", + "group": "Attract", + "from": "demo", + "to": "menu", + "trigger": "Fresh key or mouse", + "source": [ + "WOLFSRC/WL_MAIN.C:DemoLoop", + "WOLFSRC/WL_MENU.C:US_ControlPanel" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Original control-panel artwork.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic black fade with original gamepal reveal; simulation frozen.", + "sound": "Menu track 14.", + "input": "Abort demo and release its game resources.", + "evidence": [ + "classic", + "demo" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "menu-episode", + "group": "New game", + "from": "menu", + "to": "episode", + "trigger": "Choose New Game", + "source": [ + "WOLFSRC/WL_MENU.C:CP_NewGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop", + "src/engine/WL_MENU.c:DrawNewSelection" + ], + "artwork": "Episode artwork and six rows.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu selection sound.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "episode-difficulty", + "group": "New game", + "from": "episode", + "to": "difficulty", + "trigger": "Accept episode without active game", + "source": [ + "WOLFSRC/WL_MENU.C:CP_NewGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Difficulty artwork/BJ faces.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu sounds.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "episode-replace", + "group": "New game", + "from": "episode", + "to": "replace-confirm", + "trigger": "Accept episode while game active", + "source": [ + "WOLFSRC/WL_MENU.C:CP_NewGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:QuickDialog" + ], + "artwork": "CURGAME message and blinking cursor.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "20-tic cursor blink; answer release.", + "sound": "ESCPRESSEDSND / SHOOTSND by confirmation.", + "input": "Y/N/Escape; gameplay frozen.", + "evidence": [ + "classic", + "dos-pixels" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "replace-yes", + "group": "New game", + "from": "replace-confirm", + "to": "difficulty", + "trigger": "Y released", + "source": [ + "WOLFSRC/WL_MENU.C:CP_NewGame", + "WOLFSRC/WL_MENU.C:Confirm" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Restore destination selection.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Confirmation sounds.", + "input": "Keep quick slot until difficulty accepted.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "replace-no", + "group": "New game", + "from": "replace-confirm", + "to": "menu", + "trigger": "N/Escape", + "source": [ + "WOLFSRC/WL_MENU.C:CP_NewGame", + "WOLFSRC/WL_MENU.C:Confirm" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Restore destination selection.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Confirmation sounds.", + "input": "Keep quick slot until difficulty accepted.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "difficulty-setup", + "group": "New game", + "from": "difficulty", + "to": "setup", + "trigger": "Accept difficulty", + "source": [ + "WOLFSRC/WL_MENU.C:CP_NewGame", + "WOLFSRC/WL_GAME.C:SetupGameLevel" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ChangeScreen", + "src/engine/WL_PLAY.c:GameStartSelected" + ], + "artwork": "Play border, status bar, first floor.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Setup while simulation blocked.", + "sound": "Start level music.", + "input": "Reset quick slot and input.", + "evidence": [ + "campaign", + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "episode-back", + "group": "New game", + "from": "episode", + "to": "menu", + "trigger": "Escape", + "source": [ + "WOLFSRC/WL_MENU.C:CP_NewGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Restore parent artwork.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Escape sound.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "difficulty-back", + "group": "New game", + "from": "difficulty", + "to": "episode", + "trigger": "Escape", + "source": [ + "WOLFSRC/WL_MENU.C:CP_NewGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Restore parent artwork.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Escape sound.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "setup-psyched", + "group": "Loading", + "from": "setup", + "to": "psyched", + "trigger": "New level, ordinary load, warp or secret routing", + "source": [ + "WOLFSRC/WL_GAME.C:GameLoop", + "WOLFSRC/WL_INTER.C:PreloadGraphics" + ], + "implementation": [ + "src/engine/WL_INTER.c:StartPreloadGraphics" + ], + "artwork": "GETPSYCHEDPIC (48,56), index 127 background; retained HUD.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic fade in, real uncached page reads (\u226432 per frontend update).", + "sound": "Level music continues.", + "input": "Block simulation and input.", + "evidence": [ + "loading", + "dos-pixels" + ], + "status": "partial", + "gaps": [ + "cache", + "presentation" + ] + }, + { + "id": "psyched-progress", + "group": "Loading", + "from": "psyched", + "to": "psyched", + "trigger": "Each successfully cached non-sparse page", + "source": [ + "WOLFSRC/WL_INTER.C:PreloadUpdate", + "WOLFSRC/ID_PM.C:PM_Preload" + ], + "implementation": [ + "src/engine/WL_INTER.c:PreloadUpdate", + "src/engine/WL_INTER.c:StepPreloadGraphics" + ], + "artwork": "214\u00d72 bar (53,101); black remainder, 0x37 fill, 0x32 highlight except last column.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Only actual uncached pages advance; no artificial minimum.", + "sound": "Level track.", + "input": "No Escape cancellation in DOS callback.", + "evidence": [ + "loading", + "dos-pixels" + ], + "status": "partial", + "gaps": [ + "cache", + "presentation" + ] + }, + { + "id": "psyched-reveal", + "group": "Loading", + "from": "psyched", + "to": "reveal", + "trigger": "Cache complete then fresh acknowledgement or timeout", + "source": [ + "WOLFSRC/WL_INTER.C:PreloadGraphics" + ], + "implementation": [ + "src/engine/WL_INTER.c:StepPreloadGraphics" + ], + "artwork": "Restore bevel and game view while black.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "70-tic wait, 30-tic fade out; gameplay geometry selected while black.", + "sound": "Level track.", + "input": "Discard earlier presses; require fresh acknowledgement.", + "evidence": [ + "loading" + ], + "status": "partial", + "gaps": [ + "cache", + "entry-fizzle", + "presentation" + ] + }, + { + "id": "reveal-game", + "group": "Loading", + "from": "reveal", + "to": "gameplay", + "trigger": "Reveal completes", + "source": [ + "WOLFSRC/WL_PLAY.C:PlayLoop", + "WOLFSRC/WL_GAME.C:GameLoop" + ], + "implementation": [ + "src/engine/WL_INTER.c:StepPreloadGraphics", + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Current viewport/HUD, Enhanced geometry fixed before visible frame.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Native 30-tic palette reveal replaces DOS entry fizzle.", + "sound": "Level track.", + "input": "Clear keys; reset simulation clock before control capture.", + "evidence": [ + "loading" + ], + "status": "partial", + "gaps": [ + "entry-fizzle", + "presentation" + ] + }, + { + "id": "game-pause", + "group": "Pause", + "from": "gameplay", + "to": "pause", + "trigger": "Pause key", + "source": [ + "WOLFSRC/WL_PLAY.C:CheckKeys" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "PAUSEDPIC at (128,64) over game.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Immediate picture; freeze simulation.", + "sound": "SD_MusicOff; native preserves stream position.", + "input": "Fresh acknowledgement only.", + "evidence": [ + "classic", + "dos-pixels" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "pause-game", + "group": "Pause", + "from": "pause", + "to": "gameplay", + "trigger": "Fresh key", + "source": [ + "WOLFSRC/WL_PLAY.C:CheckKeys" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Redraw game without overlay.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Clock rebased; no catch-up.", + "sound": "Restore prior paused state.", + "input": "Clear ack and held input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "game-menu", + "group": "Pause", + "from": "gameplay", + "to": "menu", + "trigger": "Escape", + "source": [ + "WOLFSRC/WL_PLAY.C:CheckKeys", + "WOLFSRC/WL_MENU.C:US_ControlPanel" + ], + "implementation": [ + "src/engine/WL_MAIN.c:Transition" + ], + "artwork": "Original menu on 4:3 interface canvas.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu track.", + "input": "Freeze gameplay; clear input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "menu-game", + "group": "Pause", + "from": "menu", + "to": "gameplay", + "trigger": "Back to Game", + "source": [ + "WOLFSRC/WL_MENU.C:US_ControlPanel" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ChangeScreen" + ], + "artwork": "Restore viewport/HUD.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Restore level track.", + "input": "Reset simulation clock.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "save-panel", + "group": "Storage", + "from": "gameplay", + "to": "save", + "trigger": "F2 or menu Save", + "source": [ + "WOLFSRC/WL_MENU.C:CP_SaveGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Original Saving/Loading slot artwork with six portable slots.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu music/cursor sounds.", + "input": "Saving restricted to living playable game.", + "evidence": [ + "save", + "classic" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "load-panel", + "group": "Storage", + "from": "gameplay", + "to": "load", + "trigger": "F3 or menu Load", + "source": [ + "WOLFSRC/WL_MENU.C:CP_LoadGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Original Saving/Loading slot artwork with six portable slots.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu music/cursor sounds.", + "input": "Saving restricted to living playable game.", + "evidence": [ + "save", + "classic" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "menu-save", + "group": "Storage", + "from": "menu", + "to": "save", + "trigger": "Save row", + "source": [ + "WOLFSRC/WL_MENU.C:CP_SaveGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Original Saving/Loading slot artwork with six portable slots.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu music/cursor sounds.", + "input": "Saving restricted to living playable game.", + "evidence": [ + "save", + "classic" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "menu-load", + "group": "Storage", + "from": "menu", + "to": "load", + "trigger": "Load row", + "source": [ + "WOLFSRC/WL_MENU.C:CP_LoadGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Original Saving/Loading slot artwork with six portable slots.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu music/cursor sounds.", + "input": "Saving restricted to living playable game.", + "evidence": [ + "save", + "classic" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "save-work", + "group": "Storage", + "from": "save", + "to": "disk", + "trigger": "Accept slot; edit/overwrite confirmation for save", + "source": [ + "WOLFSRC/WL_MENU.C:CP_SaveGame", + "WOLFSRC/WL_MENU.C:DrawLSAction" + ], + "implementation": [ + "src/engine/WL_SAVE_MENU.c:HandleSaveMenu" + ], + "artwork": "Original disk window and alternating disk pictures.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Nonblocking presentation phases around synchronous atomic I/O.", + "sound": "Menu effects; loading restores level music.", + "input": "Confirmation answer release; validation errors preserve active game.", + "evidence": [ + "save", + "interface", + "dos-pixels" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "load-work", + "group": "Storage", + "from": "load", + "to": "disk", + "trigger": "Accept slot; edit/overwrite confirmation for save", + "source": [ + "WOLFSRC/WL_MENU.C:CP_LoadGame", + "WOLFSRC/WL_MENU.C:DrawLSAction" + ], + "implementation": [ + "src/engine/WL_SAVE_MENU.c:HandleSaveMenu" + ], + "artwork": "Original disk window and alternating disk pictures.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Nonblocking presentation phases around synchronous atomic I/O.", + "sound": "Menu effects; loading restores level music.", + "input": "Confirmation answer release; validation errors preserve active game.", + "evidence": [ + "save", + "interface", + "dos-pixels" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "ordinary-load-setup", + "group": "Storage", + "from": "disk", + "to": "setup", + "trigger": "Ordinary load succeeds", + "source": [ + "WOLFSRC/WL_MENU.C:CP_LoadGame", + "WOLFSRC/WL_GAME.C:GameLoop" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop", + "src/engine/WL_PLAY.c:GameRestoreClock" + ], + "artwork": "Retain saved game and current display settings.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Ordinary load requests Get Psyched.", + "sound": "Restore saved logical digi mode and level track.", + "input": "Clear input; no gameplay advance.", + "evidence": [ + "save", + "loading" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "save-return", + "group": "Storage", + "from": "disk", + "to": "gameplay", + "trigger": "Save succeeds", + "source": [ + "WOLFSRC/WL_MENU.C:CP_SaveGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Redraw game and border.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Finish disk phase; resume clock.", + "sound": "Level track.", + "input": "No reused save key.", + "evidence": [ + "save", + "classic" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "save-cancel", + "group": "Storage", + "from": "save", + "to": "menu", + "trigger": "Escape from ordinary menu operation", + "source": [ + "WOLFSRC/WL_MENU.C:CP_SaveGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller; F-key caller returns directly to gameplay.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Escape sound.", + "input": "No slot established on cancel.", + "evidence": [ + "classic", + "save" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "load-cancel", + "group": "Storage", + "from": "load", + "to": "menu", + "trigger": "Escape from ordinary menu operation", + "source": [ + "WOLFSRC/WL_MENU.C:CP_LoadGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller; F-key caller returns directly to gameplay.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Escape sound.", + "input": "No slot established on cancel.", + "evidence": [ + "classic", + "save" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "quicksave", + "group": "Storage", + "from": "gameplay", + "to": "quick-disk", + "trigger": "F8 with established valid slot", + "source": [ + "WOLFSRC/WL_MENU.C:CP_CheckQuick" + ], + "implementation": [ + "src/engine/WL_MAIN.c:QuickSave" + ], + "artwork": "Saving activity window.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Start/work/finish phases; no confirmation.", + "sound": "Effects; no gameplay advancement.", + "input": "First-use F8 opens ordinary selection instead.", + "evidence": [ + "classic", + "interface" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "quickload-confirm", + "group": "Storage", + "from": "gameplay", + "to": "quick-confirm", + "trigger": "F9 established slot", + "source": [ + "WOLFSRC/WL_MENU.C:CP_CheckQuick" + ], + "implementation": [ + "src/engine/WL_MAIN.c:QuickDialog" + ], + "artwork": "Named quickload message in 160-pixel area.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Blink/release confirmation.", + "sound": "Confirmation effects.", + "input": "Y/N/Escape; invalid slot opens ordinary selection.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "quickload-yes", + "group": "Storage", + "from": "quick-confirm", + "to": "quick-disk", + "trigger": "Y released", + "source": [ + "WOLFSRC/WL_MENU.C:CP_LoadGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:QuickActivity" + ], + "artwork": "Loading disk artwork.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Synchronous validated load during work phase.", + "sound": "Restore level music.", + "input": "Revalidate file at load time.", + "evidence": [ + "classic", + "save" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "quickload-no", + "group": "Storage", + "from": "quick-confirm", + "to": "gameplay", + "trigger": "N/Escape", + "source": [ + "WOLFSRC/WL_MENU.C:CP_CheckQuick" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Restore gameplay.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Level track.", + "input": "Preserve active game.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "quick-resume", + "group": "Storage", + "from": "quick-disk", + "to": "gameplay", + "trigger": "Established quick operation succeeds", + "source": [ + "WOLFSRC/WL_MENU.C:CP_LoadGame", + "WOLFSRC/WL_MENU.C:CP_CheckQuick" + ], + "implementation": [ + "src/engine/WL_MAIN.c:GamePreloadConsumed" + ], + "artwork": "Restore border/game; no Get Psyched.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Direct play-loop return, clock reset.", + "sound": "Level track.", + "input": "No simulation during disk phases.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "storage-error", + "group": "Storage", + "from": "quick-disk", + "to": "message", + "trigger": "Load/write fails validation or I/O", + "source": [ + "WOLFSRC/WL_MENU.C:CP_LoadGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:QuickDialog" + ], + "artwork": "Native explanatory error message.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Wait for acknowledgement.", + "sound": "No new game sound.", + "input": "Retain active game, file and rankings where supported.", + "evidence": [ + "save", + "classic" + ], + "status": "partial", + "gaps": [ + "storage" + ] + }, + { + "id": "message-return", + "group": "Storage", + "from": "message", + "to": "gameplay", + "trigger": "Fresh key", + "source": [ + "WOLFSRC/WL_PLAY.C:CheckKeys" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Redraw game.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Clock rebase.", + "sound": "Restore level track.", + "input": "Consume acknowledgement.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "death-turn", + "group": "Death", + "from": "gameplay", + "to": "death-turn", + "trigger": "Health reaches zero or End Game", + "source": [ + "WOLFSRC/WL_GAME.C:Died" + ], + "implementation": [ + "src/engine/WL_PLAY.c:Died" + ], + "artwork": "Held weapon sentinel -1; retain HUD weapon icon.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "2 degrees/tic; shortest arc; 180\u00b0 chooses negative; float intermediate atan2.", + "sound": "Stop music; PLAYERDEATHSND.", + "input": "Turn/fizzle input discarded.", + "evidence": [ + "death", + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "death-fizzle", + "group": "Death", + "from": "death-turn", + "to": "red-fizzle", + "trigger": "Attacker angle reached", + "source": [ + "WOLFSRC/WL_GAME.C:Died", + "WOLFSRC/ID_VH.C:FizzleFade" + ], + "implementation": [ + "src/engine/WL_PLAY.c:Died" + ], + "artwork": "Index 4 with 17-bit polynomial.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Enter fizzle on final turn tic; 64000/70 candidates per tic.", + "sound": "Death sound continues.", + "input": "Unabortable fizzle.", + "evidence": [ + "death" + ], + "status": "partial", + "gaps": [ + "fizzle-clip", + "presentation" + ] + }, + { + "id": "death-ack", + "group": "Death", + "from": "red-fizzle", + "to": "death-ack", + "trigger": "Polynomial completes", + "source": [ + "WOLFSRC/WL_GAME.C:Died" + ], + "implementation": [ + "src/engine/WL_PLAY.c:Died" + ], + "artwork": "Red viewport/HUD retained.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "100-tic wait or fresh acknowledgement. DOS then calls SD_WaitSoundDone for the active FM/PC effect; native has no separate completion gate.", + "sound": "Death sound continues; sound-enabled continuation timing has not received an executed-DOS comparison.", + "input": "Clear turn/fizzle presses.", + "evidence": [ + "death" + ], + "status": "partial", + "gaps": [ + "presentation", + "audio" + ] + }, + { + "id": "death-restart", + "group": "Death", + "from": "death-ack", + "to": "restart", + "trigger": "Lives remain", + "source": [ + "WOLFSRC/WL_GAME.C:Died", + "WOLFSRC/WL_GAME.C:GameLoop" + ], + "implementation": [ + "src/engine/WL_PLAY.c:Died" + ], + "artwork": "Pistol, 100 health, STARTAMMO, no keys; entry score.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Rebuild same level; skip Get Psyched.", + "sound": "Restart level track.", + "input": "Clear held/ack input.", + "evidence": [ + "death", + "campaign" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "restart-reveal", + "group": "Death", + "from": "restart", + "to": "gameplay", + "trigger": "Level rebuild succeeds", + "source": [ + "WOLFSRC/WL_GAME.C:GameLoop" + ], + "implementation": [ + "src/engine/WL_PLAY.c:Died" + ], + "artwork": "Original play border/HUD.", + "palette": "Original gamepal; no native restart fade/fizzle.", + "timing": "DOS sets fizzlein for the same-floor restart; Revive redraws the game immediately without a separate reveal phase.", + "sound": "Level track.", + "input": "Rebase clock.", + "evidence": [ + "death" + ], + "status": "partial", + "gaps": [ + "entry-fizzle", + "presentation" + ] + }, + { + "id": "death-final", + "group": "Death", + "from": "death-ack", + "to": "qualification", + "trigger": "Lives become negative", + "source": [ + "WOLFSRC/WL_GAME.C:GameLoop", + "WOLFSRC/WL_INTER.C:CheckHighScore" + ], + "implementation": [ + "src/engine/WL_MAIN.c:HighScores_Insert" + ], + "artwork": "No Game Over card in this DOS source.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic black fade with original gamepal reveal; simulation frozen.", + "sound": "Score music 23.", + "input": "Clear input.", + "evidence": [ + "classic", + "scores" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "exit-completion", + "group": "Progression", + "from": "gameplay", + "to": "completion", + "trigger": "Normal elevator exit", + "source": [ + "WOLFSRC/WL_GAME.C:GameLoop", + "WOLFSRC/WL_INTER.C:LevelCompleted" + ], + "implementation": [ + "src/engine/WL_PLAY.c:GameStep", + "src/engine/WL_INTER.c:StartLevelIntermission" + ], + "artwork": "Original floor completed, ratios, bonus and BJ breathing.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Source-based counters, sound waits and 30-VBL boundaries.", + "sound": "Completion music/effects.", + "input": "First press skips counts; separate press continues.", + "evidence": [ + "campaign" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "secret-completion", + "group": "Progression", + "from": "gameplay", + "to": "secret-completion", + "trigger": "Secret elevator exit", + "source": [ + "WOLFSRC/WL_GAME.C:GameLoop" + ], + "implementation": [ + "src/engine/WL_PLAY.c:GameStep" + ], + "artwork": "Normal-floor completion before secret routing.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Intermission counters/ack.", + "sound": "Completion music/effects.", + "input": "Separate continuation acknowledgement.", + "evidence": [ + "campaign", + "loading" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "next-setup", + "group": "Progression", + "from": "completion", + "to": "setup", + "trigger": "Intermission acknowledged", + "source": [ + "WOLFSRC/WL_GAME.C:GameLoop" + ], + "implementation": [ + "src/engine/WL_PLAY.c:GameStep" + ], + "artwork": "Next floor; retain inventory, reset keys.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "oldscore updated; setup/preload.", + "sound": "Next floor music.", + "input": "Clear ack.", + "evidence": [ + "campaign", + "loading" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "secret-entry", + "group": "Progression", + "from": "secret-completion", + "to": "setup", + "trigger": "Intermission acknowledged", + "source": [ + "WOLFSRC/WL_GAME.C:GameLoop" + ], + "implementation": [ + "src/engine/WL_PLAY.c:GameStep" + ], + "artwork": "Route to floor 9 (zero based).", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Ordinary setup/preload.", + "sound": "Secret floor track.", + "input": "No input carry.", + "evidence": [ + "campaign", + "loading" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "secret-return", + "group": "Progression", + "from": "completion", + "to": "setup", + "trigger": "Leaving mapon 9", + "source": [ + "WOLFSRC/WL_GAME.C:ElevatorBackTo", + "WOLFSRC/WL_GAME.C:GameLoop" + ], + "implementation": [ + "src/engine/WL_PLAY.c:GameStep" + ], + "artwork": "Secret floor completed card and 15000 bonus.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Episode-specific ElevatorBackTo; ordinary preload.", + "sound": "Destination track.", + "input": "Separate acknowledgement.", + "evidence": [ + "campaign", + "loading" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "boss-victory", + "group": "Victory", + "from": "gameplay", + "to": "boss-replay", + "trigger": "Boss dies / victory tile", + "source": [ + "WOLFSRC/WL_ACT2.C:A_StartDeathCam", + "WOLFSRC/WL_INTER.C:Victory" + ], + "implementation": [ + "src/engine/WL_VICTORY.c:DeathCameraActive", + "src/engine/WL_PLAY.c:GameStep" + ], + "artwork": "BJ run/jump or boss death-camera/replay by episode.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Original actor states; logical digi death delay 140 versus 5 tics.", + "sound": "Boss effects and victory track.", + "input": "No save during cinematic.", + "evidence": [ + "finale" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "victory-stats", + "group": "Victory", + "from": "boss-replay", + "to": "victory", + "trigger": "Cinematic finishes", + "source": [ + "WOLFSRC/WL_INTER.C:Victory" + ], + "implementation": [ + "src/engine/WL_INTER.c:DrawVictory", + "src/engine/WL_PLAY.c:GameStep" + ], + "artwork": "YOU WIN, eight-floor averages/time/code and HUD.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic black fade with original gamepal reveal; simulation frozen.", + "sound": "Victory track.", + "input": "Fresh acknowledgement.", + "evidence": [ + "finale" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "victory-article", + "group": "Victory", + "from": "victory", + "to": "article", + "trigger": "Acknowledge victory statistics", + "source": [ + "WOLFSRC/WL_INTER.C:Victory", + "WOLFSRC/WL_TEXT.C:EndText" + ], + "implementation": [ + "src/engine/WL_TEXT.c:StartEndText" + ], + "artwork": "Original ending article text/pictures.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Native page state; DOS layout commands retained.", + "sound": "Ending music.", + "input": "Arrows/Enter/PageUp/Down; Escape exits.", + "evidence": [ + "finale" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "article-scores", + "group": "Victory", + "from": "article", + "to": "qualification", + "trigger": "Last page/escape", + "source": [ + "WOLFSRC/WL_TEXT.C:EndText", + "WOLFSRC/WL_GAME.C:GameLoop" + ], + "implementation": [ + "src/engine/WL_TEXT.c:StepEndText", + "src/engine/WL_MAIN.c:HighScores_Insert" + ], + "artwork": "Original high-score panel.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic black fade with original gamepal reveal; simulation frozen.", + "sound": "Score music 23.", + "input": "Clear article input.", + "evidence": [ + "finale", + "scores" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "qualify", + "group": "High scores", + "from": "qualification", + "to": "name-entry", + "trigger": "Strict score/floor qualification", + "source": [ + "WOLFSRC/WL_INTER.C:CheckHighScore", + "WOLFSRC/ID_US_1.C:US_LineInput" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ChangeScreen", + "src/engine/WL_HIGHSCORES.c:HighScores_Insert" + ], + "artwork": "Seven-entry table, blank inserted name and I-bar.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic reveal; source editor limits.", + "sound": "Score track.", + "input": "57-character / 100-pixel pre-insertion limits; Enter/Escape.", + "evidence": [ + "scores" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "not-qualified", + "group": "High scores", + "from": "qualification", + "to": "results", + "trigger": "No rank", + "source": [ + "WOLFSRC/WL_INTER.C:CheckHighScore" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ChangeScreen" + ], + "artwork": "Seven-entry table.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "500-tic hold after 30-tic reveal.", + "sound": "Score track.", + "input": "Any fresh key continues.", + "evidence": [ + "scores", + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "name-save", + "group": "High scores", + "from": "name-entry", + "to": "title", + "trigger": "Enter or Escape finishes editor", + "source": [ + "WOLFSRC/WL_INTER.C:CheckHighScore" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop", + "src/engine/WL_HIGHSCORES.c:HighScores_Save" + ], + "artwork": "Title after entry; Escape keeps inserted blank name.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic black fade with original gamepal reveal; simulation frozen.", + "sound": "Title track.", + "input": "Atomic native persistence; failure retains session rankings and reports message.", + "evidence": [ + "scores" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "results-title", + "group": "High scores", + "from": "results", + "to": "title", + "trigger": "Timeout/fresh key", + "source": [ + "WOLFSRC/WL_INTER.C:CheckHighScore", + "WOLFSRC/WL_MAIN.C:DemoLoop" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Title/attract cycle.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "30-tic black fade with original gamepal reveal; simulation frozen.", + "sound": "Title track.", + "input": "Consume acknowledgement.", + "evidence": [ + "scores", + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "quit-menu", + "group": "Quit", + "from": "menu", + "to": "quit-confirm", + "trigger": "Quit row/Escape or F10", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Quit", + "WOLFSRC/WL_MENU.C:CP_CheckQuick" + ], + "implementation": [ + "src/engine/WL_MAIN.c:QuitMessage", + "src/engine/WL_MAIN.c:QuickDialog" + ], + "artwork": "Nine original sayings; WindowH 200 menu / 160 gameplay.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "20-tic cursor blink; wait for answer release.", + "sound": "Confirmation sound.", + "input": "Y/N/Escape, keyboard only; separate UI entropy protects gameplay RNG.", + "evidence": [ + "classic", + "dos-pixels" + ], + "status": "partial", + "gaps": [ + "ui-rng", + "presentation" + ] + }, + { + "id": "quit-game", + "group": "Quit", + "from": "gameplay", + "to": "quit-confirm", + "trigger": "Quit row/Escape or F10", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Quit", + "WOLFSRC/WL_MENU.C:CP_CheckQuick" + ], + "implementation": [ + "src/engine/WL_MAIN.c:QuitMessage", + "src/engine/WL_MAIN.c:QuickDialog" + ], + "artwork": "Nine original sayings; WindowH 200 menu / 160 gameplay.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "20-tic cursor blink; wait for answer release.", + "sound": "Confirmation sound.", + "input": "Y/N/Escape, keyboard only; separate UI entropy protects gameplay RNG.", + "evidence": [ + "classic", + "dos-pixels" + ], + "status": "partial", + "gaps": [ + "ui-rng", + "presentation" + ] + }, + { + "id": "quit-no", + "group": "Quit", + "from": "quit-confirm", + "to": "menu", + "trigger": "N/Escape from menu", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Quit" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Restore menu; F10 caller restores gameplay.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Menu redraw/return fade.", + "sound": "Menu or level track.", + "input": "Consume answer.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "quit-yes", + "group": "Quit", + "from": "quit-confirm", + "to": "exit", + "trigger": "Y released", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Quit" + ], + "implementation": [ + "src/engine/WL_MAIN.c:Transition" + ], + "artwork": "Menu dark-red fade then SDL shutdown.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic fade; portable resource teardown.", + "sound": "Stop music and sound before fade.", + "input": "No reused key; window close exits directly.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "hardware", + "presentation" + ] + }, + { + "id": "panel-sound", + "group": "Other panels", + "from": "menu", + "to": "sound", + "trigger": "Menu selection or corresponding F key", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Sound" + ], + "implementation": [ + "src/engine/WL_MENU.c:BeginSoundSettings" + ], + "artwork": "Original sound labels plus independent native volumes", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu effects; boss key mutes music.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "audio" + ], + "status": "partial", + "gaps": [ + "audio", + "presentation" + ] + }, + { + "id": "return-sound", + "group": "Other panels", + "from": "sound", + "to": "menu", + "trigger": "Escape/accept; direct F-key caller returns to game", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Sound" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Restore caller track.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "audio" + ], + "status": "partial", + "gaps": [ + "audio", + "presentation" + ] + }, + { + "id": "panel-controls", + "group": "Other panels", + "from": "menu", + "to": "controls", + "trigger": "Menu selection or corresponding F key", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Control" + ], + "implementation": [ + "src/engine/WL_CONTROLS_MENU.c:BeginControlsMenu" + ], + "artwork": "Classic/Modern bindings and mouse settings", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu effects; boss key mutes music.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "interface" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + }, + { + "id": "return-controls", + "group": "Other panels", + "from": "controls", + "to": "menu", + "trigger": "Escape/accept; direct F-key caller returns to game", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Control" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Restore caller track.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "interface" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + }, + { + "id": "panel-display", + "group": "Other panels", + "from": "controls", + "to": "display", + "trigger": "Select native Display settings in Controls", + "source": [ + "WOLFSRC/WL_MENU.C:CP_ChangeView" + ], + "implementation": [ + "src/engine/WL_DISPLAY.c:BeginDisplayMenu" + ], + "artwork": "Native output settings, no DOS equivalent", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu effects; boss key mutes music.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "loading" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + }, + { + "id": "return-display", + "group": "Other panels", + "from": "display", + "to": "controls", + "trigger": "Escape to Controls", + "source": [ + "WOLFSRC/WL_MENU.C:CP_ChangeView" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Restore caller track.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "loading" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + }, + { + "id": "panel-view", + "group": "Other panels", + "from": "menu", + "to": "view", + "trigger": "Menu selection or corresponding F key", + "source": [ + "WOLFSRC/WL_MENU.C:CP_ChangeView" + ], + "implementation": [ + "src/engine/WL_VIEW.c:BeginViewMenu" + ], + "artwork": "Original sizes 4\u201319 and border preview", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu effects; boss key mutes music.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "return-view", + "group": "Other panels", + "from": "view", + "to": "menu", + "trigger": "Escape/accept; direct F-key caller returns to game", + "source": [ + "WOLFSRC/WL_MENU.C:CP_ChangeView" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Restore caller track.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "panel-boss", + "group": "Other panels", + "from": "menu", + "to": "boss", + "trigger": "Menu selection or corresponding F key", + "source": [ + "WOLFSRC/WL_MENU.C:BossKey" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ChangeScreen" + ], + "artwork": "GOODTIMES C> rendered using game font", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu effects; boss key mutes music.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + }, + { + "id": "return-boss", + "group": "Other panels", + "from": "boss", + "to": "menu", + "trigger": "Escape/accept; direct F-key caller returns to game", + "source": [ + "WOLFSRC/WL_MENU.C:BossKey" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Restore caller track.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + }, + { + "id": "jukebox", + "group": "Optional routes", + "from": "signon", + "to": "jukebox", + "trigger": "M held at startup/sign-on or --jukebox", + "source": [ + "WOLFSRC/WL_MAIN.C:DoJukebox" + ], + "implementation": [ + "src/engine/WL_MAIN.c:DemoLoopJukebox" + ], + "artwork": "Robert\u2019s Jukebox, three six-song banks.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "18 original track indices.", + "input": "Monotonic bank choice replaces DOS time.", + "evidence": [ + "hidden" + ], + "status": "partial", + "gaps": [ + "hardware", + "presentation" + ] + }, + { + "id": "jukebox-return", + "group": "Optional routes", + "from": "jukebox", + "to": "title", + "trigger": "Escape", + "source": [ + "WOLFSRC/WL_MAIN.C:DoJukebox" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Title.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Title music.", + "input": "Clear input.", + "evidence": [ + "hidden" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "debug-warp", + "group": "Optional routes", + "from": "gameplay", + "to": "warp", + "trigger": "Unlocked Tab-W", + "source": [ + "WOLFSRC/WL_DEBUG.C:DebugKeys" + ], + "implementation": [ + "src/engine/WL_MAIN.c:HiddenKeys" + ], + "artwork": "Original warp prompt.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Freeze while editing.", + "sound": "Current level track.", + "input": "Validate floors 1\u201310; Escape cancels.", + "evidence": [ + "hidden" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + }, + { + "id": "warp-setup", + "group": "Optional routes", + "from": "warp", + "to": "setup", + "trigger": "Valid floor entered", + "source": [ + "WOLFSRC/WL_GAME.C:GameLoop" + ], + "implementation": [ + "src/engine/WL_PLAY.c:GameWarp" + ], + "artwork": "Ordinary level setup and Get Psyched.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Retain inventory; restore entry score.", + "sound": "Destination track.", + "input": "Clear input.", + "evidence": [ + "hidden", + "loading" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "cheat-message", + "group": "Optional routes", + "from": "gameplay", + "to": "message", + "trigger": "MLI/BAT/debug message", + "source": [ + "WOLFSRC/WL_PLAY.C:CheckKeys", + "WOLFSRC/WL_DEBUG.C:DebugKeys" + ], + "implementation": [ + "src/engine/WL_MAIN.c:HiddenKeys" + ], + "artwork": "Original cheat/debug text.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Paused acknowledgement; MLI +42000 tics.", + "sound": "Current track.", + "input": "MLI clears score, supplies health/ammo/keys/chaingun.", + "evidence": [ + "hidden" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + }, + { + "id": "asset-error", + "group": "Errors", + "from": "setup", + "to": "error", + "trigger": "Invalid/missing/corrupt level data", + "source": [ + "WOLFSRC/WL_GAME.C:SetupGameLevel" + ], + "implementation": [ + "src/engine/WL_MAIN.c:GameError" + ], + "artwork": "Native readable error.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "No simulation; release level resources.", + "sound": "Stop level music/effects.", + "input": "Fresh key to menu.", + "evidence": [ + "save" + ], + "status": "partial", + "gaps": [ + "storage" + ] + }, + { + "id": "error-menu", + "group": "Errors", + "from": "error", + "to": "menu", + "trigger": "Fresh key", + "source": [ + "WOLFSRC/WL_MAIN.C:Quit" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Control panel.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu track.", + "input": "Consume error acknowledgement.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "storage" + ] + }, + { + "id": "menu-scores", + "group": "High scores", + "from": "menu", + "to": "scores", + "trigger": "View Scores with no active game", + "source": [ + "WOLFSRC/WL_MENU.C:CP_ViewScores" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "CREDITSPIC \u2192 HIGHSCORESPIC", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu fade; wait for fresh key.", + "sound": "Title/score/level tracks selected at boundaries.", + "input": "Fresh key returns to main menu.", + "evidence": [ + "classic", + "scores" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "scores-menu", + "group": "High scores", + "from": "scores", + "to": "menu", + "trigger": "Fresh key", + "source": [ + "WOLFSRC/WL_INTER.C:CheckHighScore", + "WOLFSRC/WL_MAIN.C:DemoLoop" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Title/attract cycle.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu fade.", + "sound": "Title track.", + "input": "Consume acknowledgement.", + "evidence": [ + "scores", + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "menu-attract", + "group": "Pause", + "from": "menu", + "to": "title", + "trigger": "Back to Demo with no live game", + "source": [ + "WOLFSRC/WL_MENU.C:US_ControlPanel" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ChangeScreen" + ], + "artwork": "Original TITLEPIC and restarted attract cycle.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Title track 7.", + "input": "Clear selection input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "game-sound", + "group": "Other panels", + "from": "gameplay", + "to": "sound", + "trigger": "Corresponding F key during living gameplay", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Sound" + ], + "implementation": [ + "src/engine/WL_MENU.c:BeginSoundSettings" + ], + "artwork": "Original sound labels plus independent native volumes", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu effects; boss key mutes music.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "audio" + ], + "status": "partial", + "gaps": [ + "audio", + "presentation" + ] + }, + { + "id": "sound-game", + "group": "Other panels", + "from": "sound", + "to": "gameplay", + "trigger": "Accept/Escape from direct F-key panel", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Sound" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Restore caller track.", + "input": "Rebase game clock and clear panel input.", + "evidence": [ + "audio" + ], + "status": "partial", + "gaps": [ + "audio", + "presentation" + ] + }, + { + "id": "game-controls", + "group": "Other panels", + "from": "gameplay", + "to": "controls", + "trigger": "Corresponding F key during living gameplay", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Control" + ], + "implementation": [ + "src/engine/WL_CONTROLS_MENU.c:BeginControlsMenu" + ], + "artwork": "Classic/Modern bindings and mouse settings", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu effects; boss key mutes music.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "interface" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + }, + { + "id": "controls-game", + "group": "Other panels", + "from": "controls", + "to": "gameplay", + "trigger": "Accept/Escape from direct F-key panel", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Control" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Restore caller track.", + "input": "Rebase game clock and clear panel input.", + "evidence": [ + "interface" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + }, + { + "id": "game-view", + "group": "Other panels", + "from": "gameplay", + "to": "view", + "trigger": "Corresponding F key during living gameplay", + "source": [ + "WOLFSRC/WL_MENU.C:CP_ChangeView" + ], + "implementation": [ + "src/engine/WL_VIEW.c:BeginViewMenu" + ], + "artwork": "Original sizes 4\u201319 and border preview", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu effects; boss key mutes music.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "view-game", + "group": "Other panels", + "from": "view", + "to": "gameplay", + "trigger": "Accept/Escape from direct F-key panel", + "source": [ + "WOLFSRC/WL_MENU.C:CP_ChangeView" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Restore caller track.", + "input": "Rebase game clock and clear panel input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "game-boss", + "group": "Other panels", + "from": "gameplay", + "to": "boss", + "trigger": "Corresponding F key during living gameplay", + "source": [ + "WOLFSRC/WL_MENU.C:BossKey" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ChangeScreen" + ], + "artwork": "GOODTIMES C> rendered using game font", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Menu effects; boss key mutes music.", + "input": "Fresh arrows/hotkeys/Enter/Space; Escape returns; clear pending gameplay input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + }, + { + "id": "boss-game", + "group": "Other panels", + "from": "boss", + "to": "gameplay", + "trigger": "Accept/Escape from direct F-key panel", + "source": [ + "WOLFSRC/WL_MENU.C:BossKey" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Restore caller track.", + "input": "Rebase game clock and clear panel input.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + }, + { + "id": "save-cancel-game", + "group": "Storage", + "from": "save", + "to": "gameplay", + "trigger": "Escape from direct F2 panel", + "source": [ + "WOLFSRC/WL_MENU.C:CP_SaveGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller; F-key caller returns directly to gameplay.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Escape sound.", + "input": "No slot established on cancel.", + "evidence": [ + "classic", + "save" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "load-cancel-game", + "group": "Storage", + "from": "load", + "to": "gameplay", + "trigger": "Escape from direct F3 panel", + "source": [ + "WOLFSRC/WL_MENU.C:CP_LoadGame" + ], + "implementation": [ + "src/engine/WL_MAIN.c:ReturnPanel" + ], + "artwork": "Restore caller; F-key caller returns directly to gameplay.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Escape sound.", + "input": "No slot established on cancel.", + "evidence": [ + "classic", + "save" + ], + "status": "partial", + "gaps": [ + "storage", + "presentation" + ] + }, + { + "id": "quit-no-game", + "group": "Quit", + "from": "quit-confirm", + "to": "gameplay", + "trigger": "N/Escape from F10 confirmation", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Quit" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Restore live game and border.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Menu redraw/return fade.", + "sound": "Level track.", + "input": "Consume answer.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "end-game", + "group": "Death", + "from": "gameplay", + "to": "end-confirm", + "trigger": "F7 or End Game row", + "source": [ + "WOLFSRC/WL_MENU.C:CP_EndGame", + "WOLFSRC/WL_MENU.C:CP_CheckQuick" + ], + "implementation": [ + "src/engine/WL_MAIN.c:QuickDialog" + ], + "artwork": "Original ENDGAMESTR message and confirmation cursor.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Blink/release confirmation.", + "sound": "Confirmation effects.", + "input": "Y/N/Escape; freeze active game.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "end-menu", + "group": "Death", + "from": "menu", + "to": "end-confirm", + "trigger": "F7 or End Game row", + "source": [ + "WOLFSRC/WL_MENU.C:CP_EndGame", + "WOLFSRC/WL_MENU.C:CP_CheckQuick" + ], + "implementation": [ + "src/engine/WL_MAIN.c:QuickDialog" + ], + "artwork": "Original ENDGAMESTR message and confirmation cursor.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Blink/release confirmation.", + "sound": "Confirmation effects.", + "input": "Y/N/Escape; freeze active game.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "end-yes", + "group": "Death", + "from": "end-confirm", + "to": "death-turn", + "trigger": "Y released", + "source": [ + "WOLFSRC/WL_GAME.C:Died" + ], + "implementation": [ + "src/engine/WL_PLAY.c:Died" + ], + "artwork": "Held weapon sentinel -1; retain HUD weapon icon.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "2 degrees/tic; shortest arc; 180\u00b0 chooses negative; float intermediate atan2.", + "sound": "Stop music; PLAYERDEATHSND.", + "input": "Set lives=0, ex_died; clear quick slot and answer input.", + "evidence": [ + "death", + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "end-no", + "group": "Death", + "from": "end-confirm", + "to": "gameplay", + "trigger": "N/Escape from gameplay End Game", + "source": [ + "WOLFSRC/WL_MENU.C:CP_CheckQuick" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Restore gameplay.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "10-tic menu dark-red fade (43,0,0); simulation frozen.", + "sound": "Level track.", + "input": "Preserve active game.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "end-no-menu", + "group": "Death", + "from": "end-confirm", + "to": "menu", + "trigger": "N/Escape from menu End Game", + "source": [ + "WOLFSRC/WL_MENU.C:CP_Quit" + ], + "implementation": [ + "src/engine/WL_MAIN.c:StepDemoLoop" + ], + "artwork": "Restore menu; F10 caller restores gameplay.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Menu redraw/return fade.", + "sound": "Menu or level track.", + "input": "Consume answer.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "presentation" + ] + }, + { + "id": "preload-error", + "group": "Errors", + "from": "psyched", + "to": "error", + "trigger": "Asset read/allocation fails during preload", + "source": [ + "WOLFSRC/WL_INTER.C:PreloadGraphics" + ], + "implementation": [ + "src/engine/WL_MAIN.c:GameError" + ], + "artwork": "Native readable error.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "No simulation; release level resources.", + "sound": "Stop level music/effects.", + "input": "Fresh key to menu.", + "evidence": [ + "loading", + "save" + ], + "status": "partial", + "gaps": [ + "storage" + ] + }, + { + "id": "save-error", + "group": "Storage", + "from": "save", + "to": "save", + "trigger": "Write or overwrite fails", + "source": [ + "WOLFSRC/WL_MENU.C:CP_SaveGame", + "WOLFSRC/WL_MENU.C:DrawLSAction" + ], + "implementation": [ + "src/engine/WL_SAVE_MENU.c:HandleSaveMenu" + ], + "artwork": "Native readable error in save panel.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Acknowledge error; no gameplay advance.", + "sound": "Menu effects; loading restores level music.", + "input": "Keep prior slot and active game; retry/cancel supported.", + "evidence": [ + "save" + ], + "status": "partial", + "gaps": [ + "storage" + ] + }, + { + "id": "window-close", + "group": "Quit", + "from": "gameplay", + "to": "exit", + "trigger": "SDL quit/window close", + "source": [ + "WOLFSRC/WL_MAIN.C:Quit" + ], + "implementation": [ + "src/engine/WL_MAIN.c:DemoLoopPrepareExit" + ], + "artwork": "No additional screen.", + "palette": "Original gamepal indices; VGA-style DAC interpolation where faded.", + "timing": "Immediate normal application teardown; no confirmation.", + "sound": "Stop music and sound before fade.", + "input": "OS close exits directly from every presentation state.", + "evidence": [ + "classic" + ], + "status": "partial", + "gaps": [ + "hardware" + ] + } + ], + "references": { + "WOLFSRC/WL_MAIN.C:InitGame": { + "path": "WOLFSRC/WL_MAIN.C", + "anchor": "InitGame", + "label": "InitGame" + }, + "WOLFSRC/WL_MENU.C:IntroScreen": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "IntroScreen", + "label": "IntroScreen" + }, + "src/engine/WL_MAIN.c:DemoLoopStartupDevices": { + "path": "src/engine/WL_MAIN.c", + "anchor": "DemoLoopStartupDevices", + "label": "DemoLoopStartupDevices" + }, + "src/engine/WL_MAIN.c:DemoLoopSignon": { + "path": "src/engine/WL_MAIN.c", + "anchor": "DemoLoopSignon", + "label": "DemoLoopSignon" + }, + "WOLFSRC/WL_MAIN.C:FinishSignon": { + "path": "WOLFSRC/WL_MAIN.C", + "anchor": "FinishSignon", + "label": "FinishSignon" + }, + "WOLFSRC/WL_INTER.C:PG13": { + "path": "WOLFSRC/WL_INTER.C", + "anchor": "PG13", + "label": "PG13" + }, + "src/engine/WL_MAIN.c:SignonPrompt": { + "path": "src/engine/WL_MAIN.c", + "anchor": "SignonPrompt", + "label": "SignonPrompt" + }, + "src/engine/WL_MAIN.c:DemoLoopIntro": { + "path": "src/engine/WL_MAIN.c", + "anchor": "DemoLoopIntro", + "label": "DemoLoopIntro" + }, + "WOLFSRC/WL_MAIN.C:DemoLoop": { + "path": "WOLFSRC/WL_MAIN.C", + "anchor": "DemoLoop", + "label": "DemoLoop" + }, + "src/engine/WL_MAIN.c:StepDemoLoop": { + "path": "src/engine/WL_MAIN.c", + "anchor": "StepDemoLoop", + "label": "StepDemoLoop" + }, + "WOLFSRC/WL_GAME.C:PlayDemo": { + "path": "WOLFSRC/WL_GAME.C", + "anchor": "PlayDemo", + "label": "PlayDemo" + }, + "src/engine/WL_MAIN.c:ChangeScreen": { + "path": "src/engine/WL_MAIN.c", + "anchor": "ChangeScreen", + "label": "ChangeScreen" + }, + "WOLFSRC/WL_MENU.C:US_ControlPanel": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "US_ControlPanel", + "label": "US_ControlPanel" + }, + "WOLFSRC/WL_MENU.C:CP_NewGame": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "CP_NewGame", + "label": "CP_NewGame" + }, + "src/engine/WL_MENU.c:DrawNewSelection": { + "path": "src/engine/WL_MENU.c", + "anchor": "DrawNewSelection", + "label": "DrawNewSelection" + }, + "src/engine/WL_MAIN.c:QuickDialog": { + "path": "src/engine/WL_MAIN.c", + "anchor": "QuickDialog", + "label": "QuickDialog" + }, + "WOLFSRC/WL_MENU.C:Confirm": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "Confirm", + "label": "Confirm" + }, + "WOLFSRC/WL_GAME.C:SetupGameLevel": { + "path": "WOLFSRC/WL_GAME.C", + "anchor": "SetupGameLevel", + "label": "SetupGameLevel" + }, + "src/engine/WL_PLAY.c:GameStartSelected": { + "path": "src/engine/WL_PLAY.c", + "anchor": "GameStartSelected", + "label": "GameStartSelected" + }, + "WOLFSRC/WL_GAME.C:GameLoop": { + "path": "WOLFSRC/WL_GAME.C", + "anchor": "GameLoop", + "label": "GameLoop" + }, + "WOLFSRC/WL_INTER.C:PreloadGraphics": { + "path": "WOLFSRC/WL_INTER.C", + "anchor": "PreloadGraphics", + "label": "PreloadGraphics" + }, + "src/engine/WL_INTER.c:StartPreloadGraphics": { + "path": "src/engine/WL_INTER.c", + "anchor": "StartPreloadGraphics", + "label": "StartPreloadGraphics" + }, + "WOLFSRC/WL_INTER.C:PreloadUpdate": { + "path": "WOLFSRC/WL_INTER.C", + "anchor": "PreloadUpdate", + "label": "PreloadUpdate" + }, + "WOLFSRC/ID_PM.C:PM_Preload": { + "path": "WOLFSRC/ID_PM.C", + "anchor": "PM_Preload", + "label": "PM_Preload" + }, + "src/engine/WL_INTER.c:PreloadUpdate": { + "path": "src/engine/WL_INTER.c", + "anchor": "PreloadUpdate", + "label": "PreloadUpdate" + }, + "src/engine/WL_INTER.c:StepPreloadGraphics": { + "path": "src/engine/WL_INTER.c", + "anchor": "StepPreloadGraphics", + "label": "StepPreloadGraphics" + }, + "WOLFSRC/WL_PLAY.C:PlayLoop": { + "path": "WOLFSRC/WL_PLAY.C", + "anchor": "PlayLoop", + "label": "PlayLoop" + }, + "WOLFSRC/WL_PLAY.C:CheckKeys": { + "path": "WOLFSRC/WL_PLAY.C", + "anchor": "CheckKeys", + "label": "CheckKeys" + }, + "src/engine/WL_MAIN.c:Transition": { + "path": "src/engine/WL_MAIN.c", + "anchor": "Transition", + "label": "Transition" + }, + "WOLFSRC/WL_MENU.C:CP_SaveGame": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "CP_SaveGame", + "label": "CP_SaveGame" + }, + "WOLFSRC/WL_MENU.C:CP_LoadGame": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "CP_LoadGame", + "label": "CP_LoadGame" + }, + "WOLFSRC/WL_MENU.C:DrawLSAction": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "DrawLSAction", + "label": "DrawLSAction" + }, + "src/engine/WL_SAVE_MENU.c:HandleSaveMenu": { + "path": "src/engine/WL_SAVE_MENU.c", + "anchor": "HandleSaveMenu", + "label": "HandleSaveMenu" + }, + "src/engine/WL_PLAY.c:GameRestoreClock": { + "path": "src/engine/WL_PLAY.c", + "anchor": "GameRestoreClock", + "label": "GameRestoreClock" + }, + "src/engine/WL_MAIN.c:ReturnPanel": { + "path": "src/engine/WL_MAIN.c", + "anchor": "ReturnPanel", + "label": "ReturnPanel" + }, + "WOLFSRC/WL_MENU.C:CP_CheckQuick": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "CP_CheckQuick", + "label": "CP_CheckQuick" + }, + "src/engine/WL_MAIN.c:QuickSave": { + "path": "src/engine/WL_MAIN.c", + "anchor": "QuickSave", + "label": "QuickSave" + }, + "src/engine/WL_MAIN.c:QuickActivity": { + "path": "src/engine/WL_MAIN.c", + "anchor": "QuickActivity", + "label": "QuickActivity" + }, + "src/engine/WL_MAIN.c:GamePreloadConsumed": { + "path": "src/engine/WL_MAIN.c", + "anchor": "GamePreloadConsumed", + "label": "GamePreloadConsumed" + }, + "WOLFSRC/WL_GAME.C:Died": { + "path": "WOLFSRC/WL_GAME.C", + "anchor": "Died", + "label": "Died" + }, + "src/engine/WL_PLAY.c:Died": { + "path": "src/engine/WL_PLAY.c", + "anchor": "Died", + "label": "Died" + }, + "WOLFSRC/ID_VH.C:FizzleFade": { + "path": "WOLFSRC/ID_VH.C", + "anchor": "FizzleFade", + "label": "FizzleFade" + }, + "WOLFSRC/WL_INTER.C:CheckHighScore": { + "path": "WOLFSRC/WL_INTER.C", + "anchor": "CheckHighScore", + "label": "CheckHighScore" + }, + "src/engine/WL_MAIN.c:HighScores_Insert": { + "path": "src/engine/WL_MAIN.c", + "anchor": "HighScores_Insert", + "label": "HighScores_Insert" + }, + "WOLFSRC/WL_INTER.C:LevelCompleted": { + "path": "WOLFSRC/WL_INTER.C", + "anchor": "LevelCompleted", + "label": "LevelCompleted" + }, + "src/engine/WL_PLAY.c:GameStep": { + "path": "src/engine/WL_PLAY.c", + "anchor": "GameStep", + "label": "GameStep" + }, + "src/engine/WL_INTER.c:StartLevelIntermission": { + "path": "src/engine/WL_INTER.c", + "anchor": "StartLevelIntermission", + "label": "StartLevelIntermission" + }, + "WOLFSRC/WL_GAME.C:ElevatorBackTo": { + "path": "WOLFSRC/WL_GAME.C", + "anchor": "ElevatorBackTo", + "label": "ElevatorBackTo" + }, + "WOLFSRC/WL_ACT2.C:A_StartDeathCam": { + "path": "WOLFSRC/WL_ACT2.C", + "anchor": "A_StartDeathCam", + "label": "A_StartDeathCam" + }, + "WOLFSRC/WL_INTER.C:Victory": { + "path": "WOLFSRC/WL_INTER.C", + "anchor": "Victory", + "label": "Victory" + }, + "src/engine/WL_VICTORY.c:DeathCameraActive": { + "path": "src/engine/WL_VICTORY.c", + "anchor": "DeathCameraActive", + "label": "DeathCameraActive" + }, + "src/engine/WL_INTER.c:DrawVictory": { + "path": "src/engine/WL_INTER.c", + "anchor": "DrawVictory", + "label": "DrawVictory" + }, + "WOLFSRC/WL_TEXT.C:EndText": { + "path": "WOLFSRC/WL_TEXT.C", + "anchor": "EndText", + "label": "EndText" + }, + "src/engine/WL_TEXT.c:StartEndText": { + "path": "src/engine/WL_TEXT.c", + "anchor": "StartEndText", + "label": "StartEndText" + }, + "src/engine/WL_TEXT.c:StepEndText": { + "path": "src/engine/WL_TEXT.c", + "anchor": "StepEndText", + "label": "StepEndText" + }, + "WOLFSRC/ID_US_1.C:US_LineInput": { + "path": "WOLFSRC/ID_US_1.C", + "anchor": "US_LineInput", + "label": "US_LineInput" + }, + "src/engine/WL_HIGHSCORES.c:HighScores_Insert": { + "path": "src/engine/WL_HIGHSCORES.c", + "anchor": "HighScores_Insert", + "label": "HighScores_Insert" + }, + "src/engine/WL_HIGHSCORES.c:HighScores_Save": { + "path": "src/engine/WL_HIGHSCORES.c", + "anchor": "HighScores_Save", + "label": "HighScores_Save" + }, + "WOLFSRC/WL_MENU.C:CP_Quit": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "CP_Quit", + "label": "CP_Quit" + }, + "src/engine/WL_MAIN.c:QuitMessage": { + "path": "src/engine/WL_MAIN.c", + "anchor": "QuitMessage", + "label": "QuitMessage" + }, + "WOLFSRC/WL_MENU.C:CP_Sound": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "CP_Sound", + "label": "CP_Sound" + }, + "src/engine/WL_MENU.c:BeginSoundSettings": { + "path": "src/engine/WL_MENU.c", + "anchor": "BeginSoundSettings", + "label": "BeginSoundSettings" + }, + "WOLFSRC/WL_MENU.C:CP_Control": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "CP_Control", + "label": "CP_Control" + }, + "src/engine/WL_CONTROLS_MENU.c:BeginControlsMenu": { + "path": "src/engine/WL_CONTROLS_MENU.c", + "anchor": "BeginControlsMenu", + "label": "BeginControlsMenu" + }, + "WOLFSRC/WL_MENU.C:CP_ChangeView": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "CP_ChangeView", + "label": "CP_ChangeView" + }, + "src/engine/WL_DISPLAY.c:BeginDisplayMenu": { + "path": "src/engine/WL_DISPLAY.c", + "anchor": "BeginDisplayMenu", + "label": "BeginDisplayMenu" + }, + "src/engine/WL_VIEW.c:BeginViewMenu": { + "path": "src/engine/WL_VIEW.c", + "anchor": "BeginViewMenu", + "label": "BeginViewMenu" + }, + "WOLFSRC/WL_MENU.C:BossKey": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "BossKey", + "label": "BossKey" + }, + "WOLFSRC/WL_MAIN.C:DoJukebox": { + "path": "WOLFSRC/WL_MAIN.C", + "anchor": "DoJukebox", + "label": "DoJukebox" + }, + "src/engine/WL_MAIN.c:DemoLoopJukebox": { + "path": "src/engine/WL_MAIN.c", + "anchor": "DemoLoopJukebox", + "label": "DemoLoopJukebox" + }, + "WOLFSRC/WL_DEBUG.C:DebugKeys": { + "path": "WOLFSRC/WL_DEBUG.C", + "anchor": "DebugKeys", + "label": "DebugKeys" + }, + "src/engine/WL_MAIN.c:HiddenKeys": { + "path": "src/engine/WL_MAIN.c", + "anchor": "HiddenKeys", + "label": "HiddenKeys" + }, + "src/engine/WL_PLAY.c:GameWarp": { + "path": "src/engine/WL_PLAY.c", + "anchor": "GameWarp", + "label": "GameWarp" + }, + "src/engine/WL_MAIN.c:GameError": { + "path": "src/engine/WL_MAIN.c", + "anchor": "GameError", + "label": "GameError" + }, + "WOLFSRC/WL_MAIN.C:Quit": { + "path": "WOLFSRC/WL_MAIN.C", + "anchor": "Quit", + "label": "Quit" + }, + "WOLFSRC/WL_MENU.C:CP_ViewScores": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "void CP_ViewScores(void)", + "label": "CP_ViewScores" + }, + "WOLFSRC/WL_MENU.C:CP_EndGame": { + "path": "WOLFSRC/WL_MENU.C", + "anchor": "int CP_EndGame(void)", + "label": "CP_EndGame" + }, + "src/engine/WL_MAIN.c:DemoLoopPrepareExit": { + "path": "src/engine/WL_MAIN.c", + "anchor": "DemoLoopPrepareExit", + "label": "DemoLoopPrepareExit" + } + }, + "evidence": { + "loading": { + "scope": "Actual frontend phases, partial page counts, palette steps, fresh ack, progression/secret routing/load and stable Enhanced geometry.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "Native source/artwork oracle; DOS execution now compares controlled progress drawings, not cache duration or the continuous loading sequence.", + "refs": [ + { + "path": "tests/loading_tests.c", + "anchor": "static void Loading" + } + ] + }, + "death": { + "scope": "320 attacker/view scenarios, sentinel, rotation, tie/wrap, sound event, intermediate red fizzle and restart.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "Source-derived native assertions, not executed-DOS death frames or physical audio latency.", + "refs": [ + { + "path": "tests/loading_tests.c", + "anchor": "static void Death" + } + ] + }, + "classic": { + "scope": "F1\u2013F10, pause, replacement confirmation, quick operations, clock/RNG freeze and final death.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "No continuous executed-DOS menu journey or enabled-DOS audio comparison.", + "refs": [ + { + "path": "tests/classic_tests.c", + "anchor": "static void Keys" + } + ] + }, + "interface": { + "scope": "DOS mouse thresholds/priority/buttons, separate relative menu capture, focus/enable release and regain, idle stability, keyboard input, music pause and disk phases.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "Native operation phases replace DOS disk serialization timing.", + "refs": [ + { + "path": "tests/classic_tests.c", + "anchor": "static void Interface" + } + ] + }, + "scores": { + "scope": "Qualification/ties, editing, cancellation, persistence and corrupt-file protection.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "No executed-DOS score-entry animation comparison; native file format.", + "refs": [ + { + "path": "tests/classic_tests.c", + "anchor": "static void Scores" + } + ] + }, + "hidden": { + "scope": "MLI/BAT, portable debug tools and all three jukebox banks.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "No ISA/gameport/EMS/XMS debug emulation.", + "refs": [ + { + "path": "tests/classic_tests.c", + "anchor": "static void Hidden" + } + ] + }, + "dos-pixels": { + "scope": "30 full executed-DOS indexed frames: quit, disk, controlled Get Psyched progress, Pause art new-game message and default high scores.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "Controlled original drawing calls on a menu background, plus the original score table drawing; not gameplay composites, fades, sound, cache reads, input waits or animated name entry.", + "refs": [ + { + "path": "tests/dos_ui_reference.c", + "anchor": "int main" + } + ] + }, + "demo": { + "scope": "Four recordings, 5386 per-command DOS state hashes, Classic and Enhanced.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "Reference archive revision, view size 15 and DOS sound off only; not every gameplay branch.", + "refs": [ + { + "path": "tests/test_demo_sync.py", + "anchor": "def owned_frames" + } + ] + }, + "campaign": { + "scope": "Exit routing, secret return, inventory and restart.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "Controlled fixtures and all-map loading, not human playthrough of all 60 floors.", + "refs": [ + { + "path": "tests/campaign_tests.c", + "anchor": "static void TestProgression" + } + ] + }, + "finale": { + "scope": "Boss/BJ victory, statistics, articles and restarts.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "Source-based native coverage; no continuous executed-DOS finale comparison.", + "refs": [ + { + "path": "tests/finale_tests.c", + "anchor": "static void TestRestartAndArticles" + } + ] + }, + "signon": { + "scope": "Optional owned sign-on, capability lights, prompt and startup order.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "Native capabilities replace DOS memory/card detection; no physical VGA timing.", + "refs": [ + { + "path": "tests/test_signon.py", + "anchor": "class " + } + ] + }, + "save": { + "scope": "Persistence, CRC/field validation, failed writes, restart and deterministic continuation.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "Six native slots/version 1, not original ten-slot serialization.", + "refs": [ + { + "path": "tests/test_save.py", + "anchor": "class " + } + ] + }, + "audio": { + "scope": "IMF/OPL/PCM schedules, priorities, volumes, disabled effects/music and lifecycle.", + "observation": "Assertions available in the linked regression; current execution results are recorded separately in MILESTONE13_FINAL_FIDELITY.md.", + "limits": "Emulated OPL with native gain; no calibrated physical DAC/OPL comparison.", + "refs": [ + { + "path": "tests/audio_tests.c", + "anchor": "static void Timing" + } + ] + } + }, + "gaps": { + "presentation": { + "priority": "P1", + "title": "Continuous executed-DOS comparison incomplete", + "finding": "30 controlled indexed frames and four sound-off demo state traces do not establish all intermediate fades, gameplay composites, victory/article/name-entry or death frames.", + "close_with": "Capture synchronized original DOS intermediate framebuffer/palette/input/audio records for these journeys.", + "refs": [ + "WOLFSRC/WL_INTER.C:PreloadGraphics", + "src/engine/WL_INTER.c:StepPreloadGraphics" + ] + }, + "cache": { + "priority": "P2", + "title": "Native cache and I/O cadence", + "finding": "Native heap residency and bounded reads replace DOS main/EMS/XMS budgets and disk speed; exact page counts and duration differ.", + "close_with": "Treat as intentional adaptation; compare visual progress formula separately from hardware-dependent duration.", + "refs": [ + "WOLFSRC/ID_PM.C:PM_Preload", + "src/engine/WL_INTER.c:StepPreloadGraphics" + ] + }, + "entry-fizzle": { + "priority": "P1", + "title": "Gameplay-entry reveal differs", + "finding": "DOS GameLoop sets fizzlein; Revive uses a 30-tic palette fade after loading and redraws immediately on death restart. Neither reproduces DOS ThreeDRefresh/FizzleFade gameplay-entry reveal. This is an acknowledged visual difference, not pixel parity.", + "close_with": "Implement and independently compare DOS entry fizzle before claiming complete presentation equivalence.", + "refs": [ + "WOLFSRC/WL_GAME.C:GameLoop", + "src/engine/WL_INTER.c:StepPreloadGraphics" + ] + }, + "fizzle-clip": { + "priority": "P2", + "title": "Safe red-fizzle clipping", + "finding": "Revive clips to the active viewport; DOS FizzleFade accepts x==width/y==height and can overdraw border pixels.", + "close_with": "Retain safe clipping as an intentional difference unless a bounded compatible renderer is separately demonstrated.", + "refs": [ + "WOLFSRC/ID_VH.C:FizzleFade", + "src/engine/WL_PLAY.c:Died" + ] + }, + "storage": { + "priority": "P2", + "title": "Portable storage/error flows", + "finding": "Six versioned atomic native saves and separate score/config files replace DOS ten-slot formats. Native I/O/error and disk-flip phases differ.", + "close_with": "Document compatibility boundary; keep corruption, atomic failure and restart regressions passing.", + "refs": [ + "WOLFSRC/WL_MENU.C:CP_LoadGame", + "src/engine/WL_PLAY.c:GameRestoreClock" + ] + }, + "hardware": { + "priority": "P2", + "title": "Portable hardware, input and debug adaptations", + "finding": "No ISA/gameport/EMS/XMS detection, BIOS text mode, controller calibration or DOS timing/cache debug emulation. Native display/binding panels and startup plumbing differ.", + "close_with": "Document unsupported hardware/editions and verify actual native devices separately.", + "refs": [ + "WOLFSRC/WL_MENU.C:IntroScreen", + "src/engine/WL_MAIN.c:DemoLoopStartupDevices" + ] + }, + "ui-rng": { + "priority": "P2", + "title": "Separate UI entropy", + "finding": "Quit-message selection uses separate native UI entropy, preserving gameplay/demo RNG rather than consuming original US_RndT.", + "close_with": "Retain intentional separation and test original saying selection precedence independently.", + "refs": [ + "WOLFSRC/WL_MENU.C:CP_Quit", + "src/engine/WL_MAIN.c:QuitMessage" + ] + }, + "audio": { + "priority": "P1", + "title": "Physical FM/PCM balance unverified", + "finding": "The current wide-accumulator \u00d74 FM gain, synth and native volume controls are not calibrated against physical OPL/Sound Blaster output. Scheduling/priority tests do not establish loudness parity. DOS UpdateFace skips RNG while GETGATLINGSND is playing; the native engine intentionally retains audio-independent face/RNG updates. The four reference demos use DOS sound off. DOS Died also calls SD_WaitSoundDone after acknowledgement; native death has no separate sound-completion gate. The existing fizzle/wait usually outlasts the effect, but early acknowledgement versus FM completion is not independently verified.", + "close_with": "Measure representative enabled-DOS tracks/effects against a documented device/reference before changing gain.", + "refs": [ + "WOLFSRC/WL_MENU.C:CP_Sound", + "src/engine/WL_MENU.c:BeginSoundSettings" + ] + } + }, + "statuses": { + "source-reviewed": "Source correspondence inspected; no runtime or pixel-equivalence claim.", + "partial": "Known intentional difference or verification gap remains; see linked findings." + }, + "original_sha256": { + "WOLFSRC/ID_PM.C": "5fd7e5586635881b06a0a80c6b0f23caab2e17bcdfecb3611228d4369a6c3a2e", + "WOLFSRC/ID_US_1.C": "6a56462ac38b997f9ca8c14e24564082286e7d08b1e3fbd89607e56cf2c8b611", + "WOLFSRC/ID_VH.C": "787cc1bf483432b9b922beb69356aa134224dd1bbedd9fb8bcbaae19da8d863b", + "WOLFSRC/WL_ACT2.C": "16374a70218dceec093a83e7610cac201da0cf371cb14768f27ddc41836c24b0", + "WOLFSRC/WL_DEBUG.C": "d4635d6c6a4a5d5bc3198e01b669c9b09afe5d99196187f604c03675b36030d4", + "WOLFSRC/WL_GAME.C": "adf9b84852a04bfbd27fda62b8337dd85435562e8aa563907d0ade2e43ff7423", + "WOLFSRC/WL_INTER.C": "563f960b59b489de4aa96f3f5e749a8317ddd4752ee85d8edb8302bf84c675a2", + "WOLFSRC/WL_MAIN.C": "73a69d37497976c70031326b0ead1748a4bec330b427899393830260bdde0a00", + "WOLFSRC/WL_MENU.C": "c2ef6856a16d699ef0a68b130daaecec7e137ea2bc2c98510fa63be8951eedff", + "WOLFSRC/WL_PLAY.C": "f8ef33eea485c5b9cd91c1167f431c058190148aaaf24296e1b7656e8d9cdf31", + "WOLFSRC/WL_TEXT.C": "dc6c2ed77e0652c153020436a8cad9115f1402277c9ce58dcac20824b3bff13a" + }, + "native_ui": { + "UI_BOSS": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "panel-boss", + "return-boss", + "game-boss", + "boss-game" + ] + }, + "UI_CONFIRM": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "quit-menu", + "quit-game", + "quit-no", + "quit-yes", + "quit-no-game" + ] + }, + "UI_CONTROLS": { + "classification": "native-adaptation", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "panel-controls", + "return-controls", + "panel-display", + "return-display", + "game-controls", + "controls-game" + ] + }, + "UI_CREDITS": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "title-credits", + "credits-scores", + "credits-menu" + ] + }, + "UI_DEMO": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "scores-demo", + "demo-title", + "demo-menu" + ] + }, + "UI_DIFFICULTY": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "episode-difficulty", + "replace-yes", + "difficulty-setup", + "difficulty-back" + ] + }, + "UI_DISK": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "quicksave", + "quickload-yes", + "quick-resume", + "storage-error" + ] + }, + "UI_DISPLAY": { + "classification": "native-adaptation", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "panel-display", + "return-display" + ] + }, + "UI_DONE": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "quit-yes", + "window-close" + ] + }, + "UI_EPISODE": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "menu-episode", + "episode-difficulty", + "episode-replace", + "episode-back", + "difficulty-back" + ] + }, + "UI_ERROR": { + "classification": "native-adaptation", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "asset-error", + "error-menu", + "preload-error" + ] + }, + "UI_GAME": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "difficulty-setup", + "setup-psyched", + "psyched-progress", + "psyched-reveal", + "reveal-game", + "game-pause", + "pause-game", + "game-menu", + "menu-game", + "save-panel", + "load-panel", + "ordinary-load-setup", + "save-return", + "quicksave", + "quickload-confirm", + "quickload-no", + "quick-resume", + "message-return", + "death-turn", + "death-fizzle", + "death-ack", + "death-restart", + "restart-reveal", + "death-final", + "exit-completion", + "secret-completion", + "next-setup", + "secret-entry", + "secret-return", + "boss-victory", + "victory-stats", + "victory-article", + "article-scores", + "quit-game", + "debug-warp", + "warp-setup", + "cheat-message", + "asset-error", + "game-sound", + "sound-game", + "game-controls", + "controls-game", + "game-view", + "view-game", + "game-boss", + "boss-game", + "save-cancel-game", + "load-cancel-game", + "quit-no-game", + "end-game", + "end-yes", + "end-no", + "preload-error", + "window-close" + ] + }, + "UI_HIGHSCORES": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "credits-scores", + "scores-demo", + "attract-scores-menu" + ] + }, + "UI_JUKEBOX": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "jukebox", + "jukebox-return" + ] + }, + "UI_LOAD": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "load-panel", + "menu-load", + "load-work", + "load-cancel", + "load-cancel-game" + ] + }, + "UI_MENU": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "title-menu", + "credits-menu", + "attract-scores-menu", + "demo-menu", + "menu-episode", + "replace-no", + "episode-back", + "game-menu", + "menu-game", + "menu-save", + "menu-load", + "save-cancel", + "load-cancel", + "quit-menu", + "quit-no", + "panel-sound", + "return-sound", + "panel-controls", + "return-controls", + "panel-view", + "return-view", + "panel-boss", + "return-boss", + "error-menu", + "menu-scores", + "scores-menu", + "menu-attract", + "end-menu", + "end-no-menu" + ] + }, + "UI_MESSAGE": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "storage-error", + "message-return", + "cheat-message" + ] + }, + "UI_PAUSE": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "game-pause", + "pause-game" + ] + }, + "UI_QUICK": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "episode-replace", + "replace-yes", + "replace-no", + "quickload-confirm", + "quickload-yes", + "quickload-no", + "quit-menu", + "quit-game", + "quit-no", + "quit-yes", + "quit-no-game", + "end-game", + "end-menu", + "end-yes", + "end-no", + "end-no-menu" + ] + }, + "UI_RATING": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "signon-ack", + "rating-title" + ] + }, + "UI_RESULTS": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "death-final", + "article-scores", + "qualify", + "not-qualified", + "name-save", + "results-title" + ] + }, + "UI_SAVE": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "save-panel", + "menu-save", + "save-work", + "save-cancel", + "save-cancel-game", + "save-error" + ] + }, + "UI_SCORES": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "menu-scores", + "scores-menu" + ] + }, + "UI_SIGNON": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "startup", + "signon-ack", + "jukebox" + ] + }, + "UI_SOUND": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "panel-sound", + "return-sound", + "game-sound", + "sound-game" + ] + }, + "UI_TITLE": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "rating-title", + "title-credits", + "demo-title", + "title-menu", + "name-save", + "results-title", + "jukebox-return", + "menu-attract" + ] + }, + "UI_VIEW": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "panel-view", + "return-view", + "game-view", + "view-game" + ] + }, + "UI_WARP": { + "classification": "DOS-route", + "note": "Return destinations are caller-dependent; see transition input notes. UI_GAME includes loading, death, completion and victory substates.", + "transitions": [ + "debug-warp", + "warp-setup" + ] + } + }, + "dos_exits": { + "ex_stillplaying": { + "classification": "route", + "note": "Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case.", + "transitions": [ + "game-pause", + "game-menu" + ] + }, + "ex_completed": { + "classification": "route", + "note": "Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case.", + "transitions": [ + "exit-completion", + "next-setup" + ] + }, + "ex_died": { + "classification": "route", + "note": "Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case.", + "transitions": [ + "death-turn", + "death-final" + ] + }, + "ex_warped": { + "classification": "route", + "note": "Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case.", + "transitions": [ + "warp-setup" + ] + }, + "ex_resetgame": { + "classification": "declaration-only", + "note": "Declared but not handled as a distinct GOODTIMES GameLoop route.", + "transitions": [] + }, + "ex_loadedgame": { + "classification": "route", + "note": "Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case.", + "transitions": [ + "ordinary-load-setup" + ] + }, + "ex_victorious": { + "classification": "route", + "note": "Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case.", + "transitions": [ + "boss-victory", + "victory-stats" + ] + }, + "ex_abort": { + "classification": "route", + "note": "Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case.", + "transitions": [ + "demo-menu", + "ordinary-load-setup" + ] + }, + "ex_demodone": { + "classification": "route", + "note": "Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case.", + "transitions": [ + "demo-title" + ] + }, + "ex_secretlevel": { + "classification": "route", + "note": "Source enum route; Revive uses scoped booleans/native playstate. ex_resetgame has no active GOODTIMES GameLoop case.", + "transitions": [ + "secret-completion", + "secret-entry", + "secret-return" + ] + } + }, + "journeys": { + "New game": [ + "title-menu", + "menu-episode", + "episode-difficulty", + "difficulty-setup", + "setup-psyched", + "psyched-progress", + "psyched-reveal", + "reveal-game" + ], + "Death restart": [ + "death-turn", + "death-fizzle", + "death-ack", + "death-restart", + "restart-reveal" + ], + "Final death": [ + "death-turn", + "death-fizzle", + "death-ack", + "death-final", + "qualify", + "name-save" + ], + "Secret floor": [ + "secret-completion", + "secret-entry", + "setup-psyched", + "psyched-reveal", + "reveal-game" + ], + "Ordinary load": [ + "menu-load", + "load-work", + "ordinary-load-setup", + "setup-psyched", + "psyched-reveal", + "reveal-game" + ], + "Established quickload": [ + "quickload-confirm", + "quickload-yes", + "quick-resume" + ], + "Victory": [ + "boss-victory", + "victory-stats", + "victory-article", + "article-scores", + "not-qualified", + "results-title" + ], + "Quit": [ + "quit-menu", + "quit-yes" + ], + "Startup/attract": [ + "startup", + "signon-ack", + "rating-title", + "title-credits", + "credits-scores", + "scores-demo", + "demo-title" + ], + "End Game": [ + "end-game", + "end-yes", + "death-fizzle", + "death-ack", + "death-final", + "not-qualified", + "results-title" + ] + }, + "boundaries": [ + "- GOODTIMES registered WL6 only: no shareware locks, SPEAR/JAPAN/SPANISH layouts or non-GOODTIMES help remapping.", + "- Original software raycaster and fixed-point 70 Hz rules remain shared by Classic and Enhanced. Modern controls, interpolation, six native saves, settings/score formats and volume controls are intentional adaptations.", + "- Physical DOS CRT/DAC/OPL, native Windows/macOS, WebAssembly and Android are not certified. Dummy SDL/Wine tests establish only their stated scope. No Android controls are introduced." + ] +} diff --git a/docs/milestones/R0/PLAN.md b/docs/milestones/R0/PLAN.md new file mode 100644 index 00000000..83fa173f --- /dev/null +++ b/docs/milestones/R0/PLAN.md @@ -0,0 +1,53 @@ +# R0: baseline and test-foundation milestone + +Status: PROPOSED / NOT RUN. Goal: understand and protect existing Wolf3D Revive behaviour before changing game identity, content format or world editing. + +## R0.1 Inventory and clean build + +Tasks: inventory source tree, branches, external dependencies, content/assets, licences, map inputs, save formats, existing tests and packaging. Document actual CART SDK requirements and clean Linux/Windows build instructions. Find all distributed Wolfenstein-specific assets and references, without deleting anything. + +Acceptance: A01 source/module and asset inventory is complete with provenance status; A02 debug/release clean-checkout builds run and warnings recorded; A03 existing game smoke path documented; A04 no unverified claims about licensing or test coverage. + +## R0.2 Ownership/architecture + +Tasks: diagram current engine/platform/game/content responsibilities, state ownership, renderer/frame clock, map loading, actor logic, input and asset lifetime. Identify the smallest stable native C world operations needed later by Workshop; specify, do not implement, new APIs. + +Acceptance: A05 dependency map matches inspected source; A06 coupling and proposed extraction points are concrete; A07 Classic/Enhanced compatibility risks are listed. + +## R0.3 Deterministic headless CPU harness + +Tasks: add test runner with focused suites for tile queries, ray intersection, collision, fixed-step or existing 70-Hz timing (verify actual rules), actors, map bounds and malformed input. Headless tests must not require SDL window creation. + +Acceptance: A08 fixed inputs yield matching final state across multiple rendering rates; A09 deterministic fixtures and failure diagnostics committed; A10 no gameplay timing changes introduced as a side effect. + +## R0.4 Matched render baselines + +Tasks: script repeatable scene/camera/input captures for Classic 4:3 and Enhanced widescreen with resolution, aspect, software scaling, resize/fullscreen, HUD and door/sprite clipping cases. Compare new captures to locked baseline with a documented tolerance policy. Do not assume pixel identity where rendering platforms differ. + +Acceptance: A11 baseline images and capture metadata reproducible; A12 all required modes visually inspected; A13 automated comparisons distinguish expected platform variance from regressions. + +## R0.5 Sanitizer + profiling baseline + +Tasks: run native AddressSanitizer/UndefinedBehaviorSanitizer where toolchain permits; leak checks, lifecycle/restarts, resource error paths. Measure frame time and allocations in representative gameplay and empty scenes, with fixed host/build/mode parameters. + +Acceptance: A14 results include toolchain and exit codes; A15 all application-owned sanitizer findings resolved or blocked with explicit owner; A16 baseline benchmark raw logs stored, no invented target FPS result. + +## R0.6 CI and validation command surface + +Tasks: stable commands like `tools/test.sh` and `python3 tools/validation/run.py R0.4` only **after implementing them**; separate CPU, graphics, sanitizer and performance jobs with explicit timeouts and progress logging. Write actionable failure diagnostics and preserve output under ignored build artifacts. + +Acceptance: A17 a clean checkout can run documented automated suites; A18 requested revision selects the correct jobs and fails non-zero when required jobs fail; A19 hanging/unsupported jobs are surfaced as failed or unrun, never fake pass. + +## R0.7 Review and baseline sign-off + +Tasks: publish R0 validation report covering criteria A01–A19, source revisions, environment, exact commands, pass/fail/partial/not-run matrix, graphics captures, performance results, open issues, owner and next action. + +Acceptance: A20 all critical criteria pass for tested targets; A21 out-of-scope platforms recorded separately; A22 architecture/test review explicitly approved before R1/R2 implementation. + +## Evidence + +Suggested generated: `build/validation/R0.x/*`, command logs, JSON test summaries, screenshots, frame-time CSV. Committed report: `docs/milestones/R0/VALIDATION.md` after actual runs. This PLAN is **not** itself an execution report. + +## Review discipline + +No major engine restructuring, IP deletion, content schema migration or Workshop UI in R0. Preserve current playable functionality, Classic/Enhanced presentation and reproducible licensing provenance. Milestone is OPEN until evidenced checks pass. diff --git a/docs/milestones/R0/R0.1.md b/docs/milestones/R0/R0.1.md new file mode 100644 index 00000000..e0716217 --- /dev/null +++ b/docs/milestones/R0/R0.1.md @@ -0,0 +1,264 @@ +# R0.1: source, asset and build inventory + +Status: **PASS (Linux clean builds and regressions verified; Windows cross-build and Wine check verified)**. Audited 22 November 2026 on branch `docs/revival-roadmap-and-validation` from source commit `47db2a3`. + +This report closes revision R0.1 only. R0 remains open: R0.2-R0.7 and acceptance criteria A05-A22 have not been performed. + +## 1. Objective, scope and evidence rules + +R0.1 establishes a reproducible baseline of the active C11/SDL3 port, its historical source and local research inputs, its CART build, current test surface, and the impact of higher-resolution replacement textures. It does not change rendering, simulation, maps, formats, assets or engine architecture. + +Findings labelled **verified** were established by inspecting the named source or running the commands in section 9. **Recommendation** identifies future work, principally for R2; it is not implemented behavior. Licence/provenance entries describe repository evidence and are not legal clearance. + +Inventory totals at the audited commit: + +- 314 tracked files; 50 active `src/**/*.c` files and 40 active headers/includes. +- 16 Python test entry points and 35 C test harnesses. +- 108 tracked historical files under `WOLFSRC/`. +- Six tracked files under `third_party/` for emu8950. +- One ignored local research directory, `3rdparty/ECWolf_RMST/`; it is not part of the repository. + +## 2. Source architecture inventory + +### Application and platform boundary + +| Area | Ownership and exact entry points | Verified behavior and coupling | +| --- | --- | --- | +| Process/front end | `src/main.c`: `main`, `Usage` | Parses data/check/smoke options, starts cache/video/audio/configuration, and drives the UI and game from a monotonic loop. It directly coordinates many engine subsystems, so startup and lifecycle remain centralized. | +| SDL video/presentation | `src/platform/sdl_video.c`: `VL_Startup`, `VL_DisplaySet`, `VL_DrawScreen`, `VL_Shutdown` | Owns the SDL window, renderer, 320x200 streaming texture, optional Enhanced indexed surface/RGBA staging, display changes, screenshots and event pumping. Engine simulation does not include SDL headers. | +| SDL input/audio | `src/platform/sdl_input.c`: `IN_SDLKey`, `IN_SDLCapture`, `IN_SDLFocusLost`; `src/platform/sdl_audio.c`: `Audio_Startup`, `Audio_Pump`, `Audio_Shutdown` | Translates SDL events to logical controls and streams PCM generated by `ID_SD`. Focus/capture state is platform-owned. | +| Files/configuration | `src/platform/data_file.c`: `CA_OpenDataFile`; `src/platform/save_file.c`: `SaveFile_WriteAtomic`; `src/platform/config_file.c`: `Config_Load`, `Config_Save` | Case-insensitive but ambiguity-rejecting read-only game-data lookup; atomic native saves/config writes; SDL preference path chosen by `main`. Windows paths use UTF-16 conversion. | + +### Engine and game modules + +| Area | Files and responsibilities | +| --- | --- | +| Bounded cache/resource input | `ID_CA.c/.h` loads and Huffman-decodes graphics; `ID_FILE.c/.h` supplies bounded byte helpers; `ID_MM.c/.h` owns heap blocks; `ID_MAP.c/.h` reads Carmack/RLEW map planes; `ID_PM.c/.h` validates, caches and decodes VSWAP pages. | +| Indexed UI/video | `ID_VL.c/.h` owns the fixed 320x200 indexed framebuffer and palette; `ID_VH.c/.h`, `ID_US_1.c/.h`, `WL_MENU.c`, `WL_TEXT.c`, `WL_VIEW.c`, `WL_DISPLAY.c`, `WL_HIGHSCORES.c` draw and operate the original-style interface. | +| World/game state | `WL_GAME.c::SetupGameLevel` builds the x-major runtime tile/door representation from map planes and validates resources/enclosure. `WL_OBJECT.c` owns actor/static pools and spawn scanning. `WL_ACT1.c` owns doors/pushwalls; `WL_ACT2.c`, `WL_STATE.c`, `WL_VICTORY.c` own actor state logic and finales. | +| Player/combat | `WL_AGENT.c::TryMove`, `ClipMove`, `ControlMovement`, `ModernMovement` implement movement and collision. `WL_COMBAT.c` handles weapons, damage, bonuses and HUD. | +| Simulation/front-end state | `WL_PLAY.c::GameStep` advances authoritative game state; `WL_MAIN.c::DemoLoop` owns title/menu/attract/application state; `WL_DEMO.c` owns original four-tic demo commands; `WL_INTER.c` owns intermission/loading phases. | +| Classic renderer | `WL_DRAW.c::CastRay`, `ThreeDRefresh`, `DrawScaleds` raycast walls and select sprites; `WL_SCALE.c::ScalePost`, `DrawShape` scale 64x64 resources into the 320x200 framebuffer. `WL_ASM.c` supplies fixed-point/table behavior. | +| Enhanced renderer | `WL_PRESENT.c::WL_PresentCapture`, `WL_PresentSample` create read-only interpolated snapshots. `WL_RENDER.c::WL_RenderSnapshot`, `Scene`, `Shape` render indexed output at larger resolutions/aspects. `WL_RENDER_TARGET.c` validates caller-owned surfaces; `WL_FRAME_CLOCK.c` separates tick and presentation clocks. | +| Audio | `ID_SD.c` owns logical music/effect state and 700/140 Hz scheduling; `ID_OPL.c`/`ID_OPL_ADPCM.c` wrap the bundled emu8950 implementation; `sdl_audio.c` owns the device/stream. | +| Persistence | `WL_SAVE.c::Save_Write`, `Save_Load` capture, validate and stage complete game snapshots; `WL_SAVE_STATES.inc` is the stable state-ID registry. | + +Global mutable state remains extensive (`gamestate`, `player`, `tilemap`, `actorat`, actor/static arrays, doors, renderer buffers and UI state). This matches the fidelity-oriented port but couples simulation, loading and rendering. R0.2 should map this ownership in more detail; R0.1 does not propose or implement extraction APIs. + +## 3. Rendering, timing and gameplay pipeline + +### Raycasting and rendering + +The Classic path is `GameStep` -> `ThreeDRefresh` -> one `CastRay`/`AsmRefresh` per viewport column -> `ScalePost` for grouped wall columns -> `DrawScaleds`/`ScaleShape` for statics and actors -> weapon overlay -> SDL palette expansion/presentation. `CastRay` traverses the fixed 64x64 grid, handles ordinary walls, doors and moving pushwalls separately, computes VSWAP page/column and rejects rays escaping the map. + +The Enhanced path keeps the Classic framebuffer for UI/HUD composition but, during an active world view, `VL_DrawScreen` calls `WL_RenderSnapshot`. `Scene` resamples the same ray intersections at each target column, keeps a depth column, draws walls, then stable-sorts transparent sprites far-to-near. `WL_RenderSnapshot` centers the original 4:3 UI within the selected gameplay aspect. This path is presentation-only; snapshots copy the relevant world state so interpolation does not mutate simulation. + +### Game loop, clock and determinism + +`main` converts SDL nanoseconds to rational 70 Hz deadlines and advances at most eight ticks per outer-loop batch. `WL_PLAY.c::GameStep` uses one-tic normal updates, four-tic original demo commands, and clamps long non-demo elapsed batches to `MAXTICS` (10). Doors, pushwalls, player input, actors, audio location, palette, render and snapshot capture are ordered explicitly within each authoritative tic. Smooth rendering samples `WL_PRESENT` snapshots at display cadence; it does not alter `gamestate.TimeCount` or RNG order. + +### Movement, collision and gameplay + +`TryMove` tests the player's `MINDIST` square against map tiles/solid doors, blocking statics and nearby shootable actors. `ClipMove` attempts the combined move then slides on one axis in the preserved order. Classic and Modern controls share these collision primitives; Modern combines normalized forward/strafe translation once per tic. Doors and pushwalls use the same `tilemap` and actor reservations. Actor behavior remains table/state-driven through `WL_STATE.c`/`WL_ACT2.c`; bounded pools are checked for allocation failure. + +Hardcoded model constraints verified in source include 64x64 maps, 64 doors, fixed tile size `TILEGLOBAL=65536`, 304-column maximum Classic viewport, at most 49 collected Classic sprites (in a 50-entry local array), bounded actor/static pools, six episodes of ten map slots, fixed WL6 resource names and a 70 Hz authoritative clock. These are compatibility constraints until a later revision explicitly changes and tests them. + +## 4. Data, maps, saves and resource ownership + +### Input formats + +- `CA_Startup` requires external `VSWAP.WL6`, `GAMEMAPS.WL6`, `MAPHEAD.WL6`, `AUDIOT.WL6`, and `AUDIOHED.WL6`, then opens `VGADICT.WL6`, `VGAHEAD.WL6`, and `VGAGRAPH.WL6`. Input is read in place and capped at 32 MiB per file; graphics expansion is capped at 4 MiB. +- `ID_MAP.h::maptype` contains three 64x64 word planes plus a name/number. `CA_ReadMap` accepts only 60 WL6 map indices and map headers whose width and height are both 64. It bounds and decompresses every plane before installing it. +- `SetupGameLevel` derives the runtime x-major `tilemap[64][64]`, door list, actors/statics and area connectivity. It validates the single player start, reachable perimeter enclosure, referenced wall pages and sprite streams before play. +- VSWAP ownership is `PM_Startup`/`PM_Shutdown`; pages are cached lazily and freed on shutdown. Map ownership is `CA_CacheMap`/`CA_UncacheMap`. Graphics chunks are owned by `ID_CA`; high-resolution render surfaces and SDL textures are owned by `sdl_video.c`. + +### Save and configuration formats + +Native saves are six `slotN.w3s` files, not DOS-compatible saves. Version 1 begins with `W3RSAVE`, a 96-byte little-endian header, bounded payload (maximum 256 KiB), CRC, slot/episode/level/difficulty metadata and CRC identities for MAPHEAD/GAMEMAPS/VSWAP. Actor pointers and state pointers are serialized as validated indices/IDs, never native addresses. `Save_Load` stages and validates all state/resources before its final map install and state application. `SaveFile_WriteAtomic` uses exclusive temporary files, flush/fsync and atomic replacement/create rules. + +Configuration is a bounded TOML subset stored beside saves in the SDL preference directory. It includes controls, audio, Classic view size and display preferences; it is independent of map content and native save version. + +No editable Workshop map or content-package format exists. The current map representation is fixed legacy WL6 input plus transient native arrays; R2 must define the shared versioned content contract before R4 authoring APIs. + +## 5. Build configuration, dependencies and platforms + +`cart.toml` selects C11, GCC, the `sdl-renderer` backend, libm and strict warning flags on Linux/Windows. The default SDL root is ignored `vendor/SDL` with shared linkage. Profile `cart-sdl` reuses `../cart/vendor/SDL` statically and adds pthread; it performs no download. The active source also compiles the bundled emu8950 C sources through `ID_OPL*.c`. + +Verified local dependencies: + +- Linux x86_64, GCC 14.2.0, Python 3.13.5, CART 0.2.0. +- sibling SDL checkout with static `libSDL3.a`; project documentation records that checkout as SDL development 3.5.0 revision `08b9c5539`. +- MinGW GCC and an ignored SDL 3.4.18 x86_64 MinGW SDK for cross-compilation; Wine 10.0 for a compatibility smoke. + +CART has no native desktop debug/release selector. Its configured build command emitted both its built-in `-O0 -g` and project `-O2`; GCC applies the last optimization option, producing optimized objects with debug information. R0.1 therefore treats that clean CART build as release-like and uses the documented explicit source/link list with `-O0 -g3 -Werror` for the clean debug build. `cart doctor` cannot accept `--profile`; base doctor correctly fails because ignored `vendor/SDL` is absent. + +Windows source compatibility is supported by `_WIN32` file/path branches and the Windows section in `cart.toml`. R0.1 cross-linked all current sources with strict warnings and passed `--check-level` under Wine. This is not native physical-Windows video, audio, input, DPI or filesystem verification. + +## 6. Existing test and diagnostic coverage + +The canonical existing suite is `python3 -m unittest discover -s tests -v`; no `tools/test.sh` or revision runner exists. Python entry points compile isolated C harnesses in temporary directories using strict warnings. Synthetic graphics/audio/map archives are generated from project-authored fixture bytes and removed after tests. Setting `WOLF3D_DATA` enables owned-data comparisons without committing those files. + +The executed 153-test suite covered: + +- bounded memory/Huffman/map/VSWAP parsing, malformed/truncated/oversized resources and case ambiguity; +- all 60 owned maps at four difficulties, raycasting, collision, actors, combat, campaign progression, bosses/finales and saves; +- deterministic original demos and 70 Hz simulation across multiple presentation rates; +- Classic viewport sizes, DOS-reference UI/hash checks, Enhanced render targets/aspects, display switching/failures and SDL dummy-driver integration; +- audio metadata/decoding/scheduling/device lifecycle, configuration, atomic saves, restart/continuation and Git push protection. + +Diagnostics include finite CLI checks (`--check-assets`, `--check-ui`, `--check-level`, `--frames`), deterministic demo trace comparison, DOS transition audit, native/DOS render hashes and benchmark harnesses. Limitations: there is no single canonical wrapper, required/optional suite selection, per-stage timeout or committed R0 report generator; sanitizer and human visual checks were not part of R0.1; physical Windows was not run. + +## 7. Texture and sprite compatibility assessment + +### Local reference inventory and provenance + +The ignored `3rdparty/ECWolf_RMST/ECWolf_RMST.pk3` was enumerated read-only. It contains 1,032 PNGs: + +| Dimensions | Count | +| --- | ---: | +| 128x128 | 1,011 | +| 16x32 | 13 | +| 96x48 | 4 | +| 640x80, 1776x26, 1506x20, 104x88 | one each | + +The companion SFX archive contains 106 audio entries. The supplied readme credits many contributors and includes id Software and other game studios, but states no redistribution licence. **Provenance status: local research input, rights unverified, not distributable by this project.** The entire `/3rdparty/` directory is ignored and remained untracked. + +### Current support: fixed 64x64, not arbitrary dimensions + +The engine cannot directly load PNGs and does not support arbitrary wall/sprite dimensions. It consumes 8-bit indexed VSWAP resources: + +- `ID_PM.c::PM_Startup` requires every pre-sprite wall page to be exactly 4,096 bytes. +- `WL_DRAW.c::CastRay` derives wall texture columns with `>>10` and `&63`, returning 0-63; `ThreeDRefresh` reads `page + column*64` and requires a 4,096-byte page. +- `WL_SCALE.c::ScalePost` iterates exactly 64 wall rows and divides vertical scaling by 64. +- `PM_DecodeSprite` validates original post bounds against 64 columns/rows and decodes into fixed `pixels[4096]` and `opaque[4096]` arrays. +- Classic `DrawShape` and Enhanced `WL_RENDER.c::Shape` loop 64 source columns/rows and index `sy*64+sx`. +- Enhanced `Scene` requires 4,096-byte wall pages, converts wall height with a `64.0/height` scale, clamps rows at 63, and indexes `column*64+row`. + +### Separate compatibility findings + +**Wall textures.** Ray/world intersection and projected wall height are independent of bitmap resolution, but `rayhit.column`, VSWAP validation, page layout and both samplers are fixed to 64. A 128x128 wall cannot be substituted without changing the resource descriptor and normalized-u sampling. Merely accepting a 16,384-byte page would still select only 64 columns/rows incorrectly. + +**World-space sprites.** Projected sprite width is derived from world distance (`65536*focal/nx`) rather than source pixel count, which is the right basis for preserving a one-tile visual size. However, pixel iteration, original two-half anchoring around source columns 31/32, sprite header validation and temporary buffers are 64-specific. A 128x128 replacement should preserve the same world-space width by default and use explicit pivot/extent metadata where an asset intentionally differs; doubling pixel dimensions must not double the actor's physical or visual world size accidentally. + +**Transparency.** Original sprites use post commands plus a separate boolean opacity plane, so palette index zero may be opaque. PNG alpha cannot be treated as a zero-colour key. A future loader must preserve explicit alpha/opacity, define indexed-palette conversion or a renderer format boundary, and test opaque zero, partial/absent alpha, malformed dimensions and bounded allocations. + +**Texture coordinates and scaling.** Wall u/v and sprite source coordinates must be normalized or parameterized by `width`, `height` and `stride`. Classic needs deterministic integer sampling into a 320x200 target; Enhanced may sample the same decoded resource at native output resolution. Both must retain wall flips, door/pushwall offsets, sprite pivoting, occlusion against `wallheight`/depth and stable far-to-near transparency. + +**Display modes.** Original/Classic and Enhanced select output resolution and aspect, not resource resolution. Higher-resolution source art should be a content/resource choice orthogonal to display mode. Classic may downsample it; Enhanced may expose more detail. The 4:3 UI/HUD remains centered even when the world aspect is 16:9 through 32:9. Tests must cover both renderers, all relevant aspects, view sizes, HUD/weapon overlays and screenshots; support in only Enhanced would not be general texture support. + +### R2 recommendations + +1. Keep legacy VSWAP decoding as a compatibility adapter. Introduce a bounded resource descriptor with role, width, height, stride/format, pixels, explicit opacity and pivot/scale metadata; do not infer role from dimensions. +2. Change ray hits to carry a normalized or fixed-point horizontal coordinate, then sample using the selected wall width. Parameterize vertical sampling. Preserve exact 64x64 behavior in legacy fixtures. +3. Replace fixed sprite decode buffers at the resource boundary with bounded owned images; parameterize both Classic and Enhanced sprite loops. Keep world size independent of source pixel resolution. +4. Define named resources and a manifest before adding PNG decoding. Validate maximum dimensions/bytes, integer overflow, alpha rules, missing resources and mixed packs. The 16x32/96x48/banner images are not automatically wall or world-sprite candidates. +5. Add original redistributable 64x64 and 128x128 fixtures that exercise wall flips, doors, pushwalls, transparent/opaque-zero sprites, pivots, weapons and both display modes. Do not derive fixtures from ECWolf_RMST. +6. Treat the remaster archive as measurements only until each asset's distribution rights and provenance are explicitly cleared. + +## 8. Asset/licensing inventory + +| Material | Repository state | Recorded provenance/status | +| --- | --- | --- | +| Active `src/` engine | tracked | SPDX GPL-2.0-only; basis described in `docs/LICENSING.md`. This is a project statement, not a new legal review. | +| `third_party/emu8950/` | tracked | MIT licence, upstream commit and two local patches recorded in its README. | +| SDL3 | external SDK, ignored | zlib licence per project documentation; SDK is not vendored here. | +| `WOLFSRC/`, `WOLFSRC.1`, `WOLFSRC.DAT`, DOS EXEs/objects | tracked historical snapshot | Historical notices retained. Archived binaries/tools/art objects are explicitly not claimed to be relicensed by the active-source GPL statement. Full R1 provenance review remains required. | +| `src/engine/gamepal.inc` and `GFXV_WL6.h` | tracked active inputs | Palette derived from the already tracked GAMEPAL OMF record; generated index header adapted from historical source, as documented in `docs/LICENSING.md`. | +| Commercial WL6 game data, captures, saves | external/ignored | User-supplied, read in place, never staged by the build. R0.1 used a local owned-data path only for validation. | +| ECWolf_RMST pack | external/ignored | Credits present; redistribution terms not found. Rights unverified; excluded from commits and release inputs. | +| Test fixtures | generated in temporary directories or small tracked hashes | Tests state and source inspection show synthetic/original fixture generation rather than copied commercial bytes. Owned-data paths enable additional private checks. | + +The repository contains Wolfenstein-specific historical names, source, executables and objects. R0.1 inventories them but does not assert that a redistributable original-content product is cleared. R1 remains responsible for file-by-file licence/provenance and packaging disposition. + +## 9. Commands and actual results + +Generated logs are retained locally under ignored `build/validation/R0.1/`; they are evidence paths, not committed artifacts. Builds used a detached clean worktree at commit `47db2a3`. + +| Check | Command (paths abbreviated) | Exit/result | +| --- | --- | --- | +| Base environment probe | `./build/tools/cart doctor` | 1, expected: ignored `vendor/SDL` absent. `doctor --profile` is unsupported. | +| Clean release-like Linux build | `/repo/build/tools/cart build --profile cart-sdl --verbose` in clean worktree | 0; all 50 C units linked; no compiler warnings. Log: `release-build.log`. | +| Clean debug Linux build | `gcc -std=c11 -O0 -g3 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror -Isrc -I../cart/vendor/SDL/include src/main.c src/engine/*.c src/platform/*.c ../cart/vendor/SDL/build/libSDL3.a -pthread -lm -o build/wolf3d-revive-debug` | 0; no warnings. Log: `debug-build.log`. | +| Release asset/UI/level checks | release binary with `--check-assets`, `--check-ui`, `--check-level` and owned `--data` | 0/0/0. | +| Debug level check | debug binary with `--check-level` and owned `--data` | 0. | +| Finite SDL smoke | dummy video/software renderer/audio, isolated `XDG_DATA_HOME`, release binary `--level --no-audio --frames 3` | 0. | +| Full regression | `WOLF3D_DATA=/owned/WL6 python3 -m unittest discover -s tests -v` in clean worktree | 0; 153 tests in 276.394 s; no skips. Log: `test-suite.log`. | +| Windows cross-build | `x86_64-w64-mingw32-gcc` with C11, `-O2 -g`, strict warnings as errors, all current sources and SDL3 3.4.18 import library | 0; no warnings. | +| Wine Windows level check | Windows binary with `--check-level` against owned data | 0. Fresh Wine prefix emitted a missing 32-bit `rundll32.exe` diagnostic, then the 64-bit application completed validation successfully. | + +Not run in R0.1: sanitizers (R0.5), new graphics baseline capture/human visual review (R0.4), physical Windows, Android, a complete human playthrough, or legal clearance. Existing regressions did execute their established render benchmarks and hash/reference checks; those are not substituted for the later R0 gates. + +## 10. Technical risks and automation opportunities + +| Risk | Evidence and consequence | Next action | +| --- | --- | --- | +| Fixed legacy resource geometry | 64/4,096 constants span loader, ray hit, Classic and Enhanced renderer paths. | Address through R2 resource contracts and dual-renderer fixtures, not a local constant change. | +| Global ownership/coupling | World, actors, UI and rendering use shared globals; snapshots copy large fixed arrays. | R0.2 dependency/ownership map before API extraction. | +| Legacy-only content contract | Fixed WL6 names, 60 maps and hardcoded resource indices; no manifest or editable save format. | R2 versioned map/resource/content design. | +| Licence/release uncertainty | Historical binaries/objects and research pack have different or unverified status. | R1 file-level provenance and staged-package policy. | +| Build mode ambiguity | CART desktop build lacks named debug/release modes and doctor profiles. | AUTO-01/R0.6 should expose explicit, reproducible modes and metadata. | +| Fragmented tests/evidence | Strong suite exists, but no canonical wrapper, timeout/progress contract or revision selector. | AUTO-02/03/05 in R0.3-R0.6; keep current Python entry point documented meanwhile. | +| Private data dependence | Broadest checks require a user's legal WL6 files; outputs/captures may contain protected art. | Separate redistributable synthetic gates from private compatibility jobs and keep evidence ignored. | +| Platform coverage | Cross-build/Wine succeeds, physical Windows/device behavior remains unknown. | Preserve an explicit platform matrix; do not convert Wine success to native PASS. | + +The playbook now records the verified R0.1 commands, prerequisites and missing automation. No helper script was introduced: the immediate task was completed with existing CART, CLI and unittest surfaces, while a safe canonical orchestration command remains R0.6 work. + +## 11. Acceptance criteria A01-A04 + +| ID | State | Evidence | +| --- | --- | --- | +| A01 source/module and asset inventory complete with provenance status | **PASS** | Sections 2-8 identify active/historical/third-party/local material, resource ownership, exact functions, fixed formats and provenance states, including unknown/unverified items. | +| A02 debug/release clean-checkout builds run and warnings recorded | **PASS** | Clean optimized CART and strict `-O0 -g3 -Werror` Linux builds exited 0 with no compiler warnings. Strict MinGW cross-build also exited 0. CART mode limitation is recorded rather than hidden. | +| A03 existing game smoke path documented | **PASS** | Section 9 records headless asset/UI/level checks plus a finite real SDL application smoke; all exited 0. `docs/automation/PLAYBOOK.md` records reusable commands. | +| A04 no unverified claims about licensing or test coverage | **PASS** | Sections 6, 8 and 9 distinguish executed tests, omissions, private inputs, repository statements and unverified/legal work. | + +## 12. Revision contract and review checklist + +**Prerequisites.** The audited source commit and branch are named at the top of +this report. Build prerequisites and their verified versions are in sections 5 +and 9. Private compatibility checks require a user-owned external WL6 data set; +the synthetic suite does not. + +**In scope.** Read-only source/asset/format inspection, clean builds, existing +tests and smokes, texture-resolution compatibility analysis, this evidence +report and the playbook update. **Out of scope:** runtime refactoring, new +resource/map formats, asset conversion or redistribution, new automation +frameworks, sanitizers/visual baselines belonging to later R0 revisions, and +R2 implementation. + +**Affected modules and C APIs.** No C module or API changed. Sections 2-7 list +the inspected owners and functions. The only tracked changes are documentation. + +**Fixtures/assets.** No fixture or artwork was added. Existing tests generated +their synthetic fixtures in temporary directories. Owned WL6 and ECWolf_RMST +were read-only external inputs and remained ignored. Future 128x128 fixtures +must be original and redistributable. + +**Validation/regression and failure injection.** Section 9 is the executable +validation contract for this revision. The full existing suite was the required +regression. Existing malformed-resource, injected display failure, atomic-write +failure, corrupt configuration/save and unavailable-device cases ran within +that suite; R0.1 added no new fault-injection mechanism. + +**Measured limits.** Recorded code limits include 32 MiB input files, 4 MiB +expanded graphics chunks, 4,096 VSWAP pages maximum, 64x64 maps/textures, +256 KiB save payloads and 4096x2160 Enhanced render targets. Test wall time is +reported for reproducibility, not as a performance acceptance threshold. + +**Review checklist.** Confirm that (1) no runtime or asset file changed, +(2) each A01-A04 state cites executed or inspected evidence, (3) external asset +rights remain unclaimed, (4) debug/release/CART qualifications are retained, +(5) omitted platforms and later R0 gates remain explicit, (6) commands in the +playbook exist now, and proposed commands remain labelled unimplemented, and +(7) no ignored third-party or generated artifact is staged. + +**Rollback.** Revert the documentation commit. No engine behavior, format, +dependency or user data requires migration. Ignored `build/validation/R0.1/` +evidence can be discarded independently after review. + +## 13. Outstanding issues and handoff + +- R0 is still open; do not infer sanitizer, visual baseline, CI or milestone sign-off from R0.1. +- The next approved revision is **R0.2 ownership/architecture**, starting from this inventory and acceptance A05-A07. Do not start R2 implementation from the recommendations above. +- R0.2 should begin with `git show --stat HEAD` and this report, then map global ownership and dependencies without changing behavior. +- Current branch at report creation: `docs/revival-roadmap-and-validation`. Intended tracked changes: this report and `docs/automation/PLAYBOOK.md` only. diff --git a/docs/milestones/R0/R0.2.md b/docs/milestones/R0/R0.2.md new file mode 100644 index 00000000..a0998f32 --- /dev/null +++ b/docs/milestones/R0/R0.2.md @@ -0,0 +1,558 @@ +# R0.2 Architecture and ownership mapping + +**Revision:** R0.2 + +**Branch:** `docs/revival-roadmap-and-validation` + +**Status:** PASS +**Scope:** documentation and design only; no production C or asset changes + +## Purpose + +Record the architecture that exists in the inspected source, identify ownership +and lifecycle hazards that affect later milestones, and define the smallest +native-C boundaries needed for deterministic tests, variable-sized resources, +and the Workshop. This is a map and a contract for later revisions, not an +implementation commitment. + +The principal finding is that platform isolation is already better than the +global variable count suggests. Most gameplay code is SDL-free and the test +suite already links it to only the filesystem adapters it needs. The difficult +boundary is world ownership: immutable legacy map planes, mutable session +arrays, actor pools, renderer bookkeeping, and save serialization jointly +describe one running level. + +## Revision contract + +### In scope + +- Inspect current C call direction, initialization, shutdown, resource + lifetime, global state, and test linkage. +- Map present ownership and identify concrete extraction seams. +- Describe Classic/Enhanced compatibility risks. +- Specify a minimal native-C authored-world editing interface, including + validation, transactions, stable identities, undo/redo, and persistence + boundaries, without implementing it. +- Describe a shared resource-image boundary that can later represent both + legacy 64x64 images and 128x128 content. +- Assign required, optional, and deferred changes to R1-R6. +- Update the reusable source-inspection procedure. + +### Out of scope + +- C, build-system, fixture, archive, or asset changes. +- A new map format, PNG decoder, Workshop UI, or editor implementation. +- Removal of legacy globals, a renderer rewrite, ECS, scene graph, scripting, + GPU migration, or multi-level/multi-storey world support. +- Completion claims for R0.3-R0.6 or later milestones. + +### Prerequisites + +- R0.1 baseline and its validation evidence. +- The source tree and tests at the R0.2 branch head. +- Private Wolfenstein data only for locally owned compatibility regression; no + protected input or generated capture may enter source control. + +## Current architecture + +The arrows below mean a direct call or direct data dependency observed in the +source. They do not imply a planned abstraction. + +```mermaid +flowchart TD + Main["main.c
process lifecycle"] --> CA["ID_CA / ID_MAP / ID_PM
legacy archives and caches"] + Main --> Video["sdl_video
window, targets, presentation"] + Main --> Audio["sdl_audio + ID_SD
stream and logical sound"] + Main --> Config["config_file
settings persistence"] + Main --> Loop["WL_MAIN DemoLoop"] + + SDLInput["sdl_input
physical events and capture"] --> CT["WL_CONTROLS + ID_IN
logical controls"] + CT --> Loop + Loop --> Step["WL_PLAY GameStep
70 Hz authority"] + Step --> Runtime["map/runtime globals
actors, doors, pushwalls, session"] + Step --> Classic["WL_DRAW / WL_SCALE
Classic renderer"] + Step --> Present["WL_PRESENT
previous/current snapshots"] + Present --> Enhanced["WL_RENDER
Enhanced renderer"] + + CA --> Runtime + Runtime --> Classic + Runtime --> Present + Classic --> FB["ID_VL indexed 320x200 framebuffer"] + FB --> Video + Enhanced --> Video + Runtime --> Save["WL_SAVE"] + Save --> SaveFile["save_file
filesystem adapter"] + Step --> Sound["game sound calls / ID_SD"] + Sound --> Audio +``` + +Only `main.c` and platform implementation/header files include SDL directly. +Core test harnesses compile `src/engine/*.c` with `data_file.c` and +`save_file.c`, demonstrating a real, if informal, headless boundary. Logical +controls (`WL_CONTROLS`) and logical sound state (`ID_SD`) remain on the engine +side; SDL input translates physical state into controls, while the SDL audio +stream consumes copied PCM. + +Key source anchors used for the map are: + +- `main.c::main` owns process startup, the outer loop, configuration save, and + ordered shutdown. `WL_MAIN.c::DemoLoop` owns frontend/game-loop selection. +- `WL_PLAY.c::GameStep` is the authoritative fixed-step entry. Normal play + advances one 70 Hz tic; demo paths may process four, with `MAXTICS` bounding + catch-up. It drives controls, doors, pushwalls, actors, sound requests, + rendering, and presentation capture. +- `WL_GAME.c::SetupGameLevel`/`ShutdownGameLevel`, + `ID_CA.c::CA_CacheMap`, and `ID_MAP.c::CA_ReadMap` bridge cached legacy + planes into the running level. +- `WL_AGENT.c::TryMove`/`ClipMove` and `actorat`/`tilemap` implement player + collision; actor/state code performs its own grid occupancy checks. +- `WL_DRAW.c::CastRay` and `ThreeDRefresh` are the Classic ray/render path; + `WL_DRAW.c::WL_RenderRayWorld` is the read-only ray-scene seam consumed by + `WL_RENDER.c` for Enhanced rendering. +- `WL_OBJECT.c::InitObjects`, `GetNewActor`, `SpawnActor`, and `RemoveActor` + own the fixed actor pool and its linked/free lists. `WL_ACT1.c` owns doors + and live pushwall behavior. +- `WL_SAVE.c` serializes live game state through `save_file.c`; + `config_file.c` persists user configuration separately. + +### Runtime ownership and call direction + +| State/resource | Declared/owned by | Initialized or reset by | Principal users and writers | Consequence | +|---|---|---|---|---| +| `gamestate` | `WL_OBJECT.c` | game/session startup and save/load paths | gameplay, intermission, campaign, rendering, UI, save | Session authority is globally reachable; tests must reset it explicitly. | +| `player` | `WL_GAME.c` | level setup/player spawn | agents, actors, combat, state machine, renderers, save | A live actor pointer is not an authored player-start definition. | +| `tilemap`, `areaMap`, `areabyplayer`, `spotvis` | `WL_GAME.c` / `WL_OBJECT.c` | `SetupGameLevel` derives them from cached map planes | collision, AI, ray casting, area reachability, save | Durable map cells and transient visibility/navigation data are interleaved at module scope. | +| `doorobjlist`, `doornum` | `WL_GAME.c` | level setup and door spawning | door simulation, rendering, save | Authored door placement and live door position/action need distinct representations. | +| pushwall position/direction/state | `WL_ACT1.c` | reset/setup and pushwall actions | simulation, render/save | Live motion must not be written back into authored map planes. Current code deliberately avoids doing so. | +| `objlist`, `actorat`, actor free/used lists | `WL_OBJECT.c` | `InitObjects`, spawn/remove helpers | AI, combat, collision, state, save, presentation | Slot/pointer identity is a bounded runtime-pool identity, not a stable authored object ID. | +| `statobjlist` and static counts | `WL_OBJECT.c` | level scan/spawn | gameplay, renderers, save | Static content and consumed/transient state share the runtime registry. | +| cached `maptype` planes | `ID_MAP.c` / `ID_CA` | `CA_CacheMap`; released by `CA_UncacheMap` | setup and restart source | Three fixed 64x64 legacy planes are borrowed cached input, not the mutable running world. | +| page file and page cache | `ID_PM.c` | `PM_Startup` / `PM_Shutdown` | both renderers and sound/resource code | Returned page pointers are borrowed and invalid after cache shutdown. | +| graphics chunks, sizes, picture table | `ID_CA.c` | `CA_Startup` / `CA_Shutdown` | UI, menus, Classic presentation | Cache manager owns bytes; consumers must not free or retain them across shutdown. | +| framebuffer and palette | `ID_VL.c` | CA/VL startup and palette calls | Classic renderer, UI, SDL video | Classic remains indexed 320x200; platform presentation owns conversion/display. | +| view geometry, ray/scale scratch | `WL_VIEW.c`, `WL_DRAW.c`, `WL_SCALE.c` | view setup/build tables | Classic renderer | Rendering is not re-entrant and is coupled to global dimensions and scratch state. | +| presentation snapshots | `WL_PRESENT.c` | reset/capture on game steps | Enhanced renderer/interpolation | This is a useful read-only scene seam, but it copies runtime arrays and is not an authored world. | +| window, SDL renderer/texture, wide targets, RGBA staging | `sdl_video.c` | `VL_Startup` / `VL_Shutdown` | platform presentation and Enhanced path | SDL resources stay below the platform boundary. | +| physical input/focus/capture | `sdl_input.c` | input startup/event processing | translation to `WL_CONTROLS`/`ID_IN` | Headless tests should inject logical controls, not synthesize SDL events. | +| logical audio resources/chip state | `ID_SD.c` | sound startup/shutdown | game sound requests and SDL audio bridge | Deterministic gameplay should assert sound requests/state without requiring a device. | +| SDL audio stream | `sdl_audio.c` | `Audio_Startup` / `Audio_Shutdown` | callback/queue bridge | Stream/device lifetime belongs to the platform, not the simulation. | +| menu/frontend/control state | `WL_MAIN.c` and menu modules | demo-loop/menu entry points | UI and platform video callbacks | UI state is process-level mutable state and must not become the Workshop's world model. | +| config/save data | `config_file.c`, `WL_SAVE.c` | explicit load/save | settings or runtime serialization | Existing file adapters are reusable patterns, but authored maps need versioning and atomic writes of their own. | + +Workshop and headless access decisions for those same groups are explicit: + +| State group | Workshop access | Headless manipulation today | +|---|---|---| +| Session (`gamestate`) and live `player` | No direct access. Playtest receives a derived session; player start is an authored value. | Possible but fragile: harness must initialize/reset globals in the correct order. | +| Authored tiles, doors, objects, player start | Yes, through validated world queries and transactions only. | No canonical owner yet; tests can construct legacy/runtime arrays directly but should not make that the new API. | +| Reachability, visibility, live doors/pushwalls | Read-only diagnostics at most; never persisted as authored content. | Yes after complete level/object reset; isolation is informal. | +| Actor/static pools and `actorat` | No. Session builder/spawn helpers translate authored definitions. | Yes through existing spawn/reset helpers; raw slot mutation is unsafe. | +| Legacy map planes and CA/PM/graphics caches | Import/preview through adapters and catalog IDs, never borrowed cache pointers. | Yes with archive fixtures and matched startup/shutdown; pointers cannot outlive caches. | +| Classic/Enhanced renderer and presentation buffers | Workshop rendering may consume immutable queries/snapshots; it must not own them as world state. | CPU render seams are headless; actual display/presentation needs SDL harnesses. | +| Input and audio | Workshop controller consumes logical controls and emits logical sound requests; neither belongs to the world. | Logical controls/sound are testable without a device; physical input and stream integration require SDL. | +| UI/config/save state | UI/config are outside the world. Authored persistence uses a versioned world codec plus platform file adapter. | Current save/config tests exist, but no authored-map persistence API exists. | + +`MM` owns allocations registered through its memory manager; the archive/cache +modules own the buffers they expose. In all later interfaces, ownership must be +spelled out as owned, borrowed for a call, or borrowed until catalog/world +destruction. No new API should return an unqualified raw pointer with a hidden +cache lifetime. + +### Initialization and shutdown + +```mermaid +sequenceDiagram + participant M as main + participant MM as ID_MM + participant CA as ID_CA / ID_MAP + participant V as sdl_video / ID_VL + participant A as sdl_audio / ID_SD + participant G as game level + + M->>MM: MM_Startup + M->>CA: CA_Startup + M->>CA: palette + cached startup screen + M->>G: DemoLoopStartup (asset/UI check path) + M->>G: GameProbe (level setup + Classic render + teardown) + M->>V: VL_Startup + M->>A: Audio_Startup + M->>M: Save_SetDirectory + Config_Load + M->>G: DemoLoopStartupDevices + DemoLoopStartup + loop frontend/game loop + M->>G: DemoLoop + M->>V: VW_UpdateScreen + end + M->>M: Config_Save + M->>A: Audio_Shutdown + M->>V: VL_Shutdown + M->>G: GameStop / ShutdownGameLevel + G->>CA: CA_UncacheMap + PM_Shutdown + M->>CA: CA_Shutdown + M->>MM: MM_Shutdown +``` + +`SetupGameLevel` caches the legacy map and page file, resets object registries, +copies/derives runtime tiles, locates player/doors/objects from the info plane, +validates enclosure and resource references, and builds view tables. +`ShutdownGameLevel` and `CA_Shutdown` have overlapping defensive cleanup. That +is useful for present error paths but makes lifecycle ownership implicit. +`GameProbe` is not a pure data probe: it constructs a level and invokes the +Classic renderer before tearing it down. + +The later world/catalog design should make partial construction explicit: +initialize output pointers to null, unwind only acquired stages, make destroy +safe on null/partial objects, and never require SDL to validate authored data. + +## Rendering and resource boundaries + +### What exists + +- Classic ray casting selects a wall page and a 0-63 source column, then fixed + scaler code samples 64x64 indexed data into the 320x200 framebuffer. +- Enhanced rendering uses the same gameplay intersections and fixed 4096-byte + wall/sprite assumptions, but renders the world to the platform-owned wide + target. UI/HUD presentation preserves the original 4:3 indexed surface. +- Legacy sprite decoding also assumes a 4096-pixel image plus opacity data. +- `WL_PRESENT` gives Enhanced rendering previous/current copies of tiles, + doors, statics, and actors for interpolation. +- Enhanced rendering is intended to read snapshots without changing + simulation state. Classic rendering still updates `spotvis` and actor + visible/active bookkeeping and can collect a visible bonus outside its pause + guard. Therefore "render" is not currently a universally read-only call. + +### Minimal shared image contract for R2 + +Both renderers should consume one immutable image description rather than gain +separate 128x128 loaders. The exact name belongs in the R2 contract; the +minimum semantics are: + +```c +typedef uint32_t resource_id; +typedef uint32_t palette_id; + +typedef enum resource_role { + RESOURCE_WALL, + RESOURCE_SPRITE, + RESOURCE_UI +} resource_role; + +typedef struct image_view { + resource_id id; + resource_role role; + uint16_t width; + uint16_t height; + uint32_t stride; + const uint8_t *indices; /* borrowed, immutable indexed pixels */ + const uint8_t *opacity; /* borrowed; NULL means role-defined opaque */ + palette_id palette; + int16_t pivot_x; + int16_t pivot_y; + uint32_t world_scale_num; + uint32_t world_scale_den; +} image_view; + +bool resource_image(const resource_catalog *catalog, + resource_id id, + image_view *out, + resource_error *error); +``` + +The catalog owns bytes and the view borrows them until catalog destruction. +Dimensions, stride, multiplication, pivot, scale denominator, and maximum +decoded bytes require bounded validation before a view is published. Opacity +is explicit because palette index zero is not a safe universal transparency +rule. + +The legacy VSWAP adapter should expose existing pages as 64x64 views and retain +the exact Classic sampling route. Rays should eventually carry a normalized or +fixed-point texture coordinate which each sampler maps to `width`, rather than +embedding 63 masks throughout casting/scaling. R2 must first prove pixel/hash +parity for the 64x64 adapter, then add 128x128 cases and malformed-dimension +tests. The descriptor also covers HUD and weapon sprites: Classic continues to +composite their indexed legacy views on the 320x200 surface, while Enhanced +may scale the same logical resource according to explicit pivot/world or UI +scale metadata. Workshop previews resolve the same IDs through the same +catalog. PNG alpha must be decoded into explicit opacity rather than assuming +palette index zero; actual PNG decoding, true-colour rendering, filtering, +atlases, and GPU upload are separate choices and are deferred. + +```mermaid +flowchart LR + Legacy["legacy archives / VSWAP"] --> Adapter["validated legacy adapter"] + Future["future authored content"] --> Catalog["resource catalog"] + Adapter --> Catalog + Catalog --> View["immutable image_view"] + View --> C["Classic sampler
legacy-exact 64x64 path"] + View --> E["Enhanced sampler"] + World["authored world resource IDs"] --> Catalog +``` + +## Proposed authored-world boundary + +### Ownership model + +One native-C world component is justified because durable map content needs a +single owner independent of SDL, UI callbacks, runtime actor slots, and cache +pointers. It owns authored cells, player start, doors, objects, stable IDs, and +the generation used for transaction conflict checks. The running game builds a +bounded session representation from it. Door motion, visibility, actor state, +collected items, and pushwall travel remain session state; they must not mutate +the authored definition. + +The legacy loader becomes an adapter into this model only when its milestone +approves that change. Workshop and future loaders then use the same validation +and mutation operations. Gameplay consumes a validated world; it does not call +editor operations to move live actors or doors. + +### Minimum C11 interface semantics + +The following is a semantic sketch, not a frozen header: + +```c +typedef struct world world; +typedef struct world_edit world_edit; +typedef uint64_t world_object_id; + +typedef enum world_status { + WORLD_OK, + WORLD_INVALID_ARGUMENT, + WORLD_OUT_OF_BOUNDS, + WORLD_LIMIT_EXCEEDED, + WORLD_CONFLICT, + WORLD_INVALID_CONTENT, + WORLD_IO_ERROR, + WORLD_NO_MEMORY +} world_status; + +world_status world_create(const world_limits *limits, world **out, + world_error *error); +void world_destroy(world **value); +world_status world_validate(const world *value, + const resource_catalog *resources, + world_report *report); + +world_status world_get_cell(const world *value, uint16_t x, uint16_t y, + world_cell *out); +world_status world_get_object(const world *value, world_object_id id, + world_object *out); + +world_status world_edit_begin(world *value, world_edit **out, + world_error *error); +world_status world_edit_set_wall(world_edit *edit, uint16_t x, uint16_t y, + resource_id wall, world_error *error); +world_status world_edit_clear_wall(world_edit *edit, uint16_t x, uint16_t y, + world_error *error); +world_status world_edit_place_door(world_edit *edit, uint16_t x, uint16_t y, + const world_door *door, world_error *error); +world_status world_edit_remove_door(world_edit *edit, uint16_t x, uint16_t y, + world_error *error); +world_status world_edit_place_object(world_edit *edit, + const world_object *object, + world_object_id *out_id, + world_error *error); +world_status world_edit_remove_object(world_edit *edit, world_object_id id, + world_error *error); +world_status world_edit_set_player_start(world_edit *edit, + const world_player_start *start, + world_error *error); +world_status world_edit_commit(world_edit **edit, world_report *report); +void world_edit_cancel(world_edit **edit); + +world_status world_undo(world *value, world_report *report); +world_status world_redo(world *value, world_report *report); +world_status world_decode(world_reader *input, world **out, + world_report *report); +world_status world_encode(const world *value, world_writer *output, + world_report *report); +``` + +Required behavior: + +- Coordinates and counts are checked before indexing or allocation. Initial + compatibility remains a single bounded 64x64 plane unless a later contract + explicitly expands it. +- Getters copy small value records or return documented immutable borrows; no + caller receives mutable storage. +- An edit records a bounded, deterministic delta and its base generation. + Commit validates the complete candidate and either publishes all changes or + none. A stale generation returns `WORLD_CONFLICT`. +- Initially one edit may be active per world. This avoids unneeded locking and + is sufficient for the single-threaded Workshop. +- Stable object IDs are monotonic within a world history and are not runtime + actor pointers or reusable array indices. Save/load preserves them. +- Undo/redo stores committed inverse/forward deltas in an explicitly bounded + history. A new commit after undo discards the redo tail. Allocation failure + or failed validation leaves the world and history unchanged. +- Validation reports machine-readable status, coordinate/object/resource + context, and bounded diagnostics. It checks enclosure, player-start + cardinality, tile/door/object conflicts, object and resource references, + capacity, and format/version constraints. +- Buffer/reader/writer interfaces keep core serialization independent of SDL + and filesystem policy. R6 supplies an atomic file adapter (temporary file, + flush/close, replace, recovery/error reporting) and round-trip tests. +- Destruction accepts null/partial values. No operation invokes UI callbacks, + reads input, renders, or silently repairs invalid content. + +This interface deliberately does not expose `tilemap`, `actorat`, map-plane +pointers, or renderer structs. A later session builder is the narrow seam that +translates a validated world into today's bounded runtime arrays. That permits +incremental migration without requiring a rewrite of actor logic. + +## Headless test boundaries + +### Proven today + +`tests/test_engine.py` builds CPU harnesses from engine sources with only the +platform-neutral data/save file adapters. Current non-SDL harnesses cover +engine logic, game behavior, combat, bosses, campaign/finale, demo traces, +frame clock, aspect/render targets, native render hashes, save, UI, and +intermission behavior. SDL harnesses separately cover actual video/audio, +presentation, loading, frontend/menu, controls, and full Classic/Enhanced +paths. + +The boundary is usable but state isolation is informal: harnesses manipulate +globals and depend on `InitObjects`, `GameStop`, and cache shutdown to restore +state. `WL_RenderRayWorld` and presentation snapshots are useful read-only +render seams. They are not substitutes for a world owner. + +### Required evidence by revision + +| Revision | Headless boundary and tests | SDL/visual boundary | +|---|---|---| +| R0.3 | Freeze deterministic behavior of existing global APIs: level query/collision/ray results, actor/door/pushwall ticks, restart/reset, logical control injection, and fixture diagnostics. Document complete reset order. Do not pre-implement the Workshop API. | None required except existing regression. | +| R0.4 | Use deterministic scenes/snapshots and fixed ticks to prepare comparisons. | Capture and compare actual Classic and Enhanced output at 4:3 and widescreen; retain human review where image tolerance cannot prove usability. | +| R2 | Test catalog ownership, legacy 64x64 parity, 128x128 addressing, opacity, invalid dimensions/stride/overflow/references, and partial-init cleanup without SDL. | Focused integration confirms both renderer paths consume the same validated views. | +| R4 | Test every world edit, validation error, transaction atomicity/conflict, stable ID, bounded undo/redo, allocation failure, and runtime-session build with no UI. | Workshop UI tests cover input/display only; authoring correctness remains in native headless tests. | +| R6 | Test versioning, malformed/truncated input, deterministic round trip, unknown resource IDs, write failure, atomic replacement/recovery, playtest-copy isolation, and return-to-editor state. | End-to-end Workshop/playtest usability and presentation remain SDL/human gates. | + +R0.3 should add the smallest reset/fixture helpers needed to make existing +state deterministic before any ownership migration. That gives later +refactors a behavioral oracle and avoids changing architecture and expected +behavior in the same revision. + +## Minimal milestone change map + +| Milestone | Classification | Existing module/function and proposed minimum boundary | Why / dependency / risk | Verification before or with implementation | +|---|---|---|---|---| +| R1 | **Required** | Put stable content/resource identities in the approved manifest/catalog boundary before values reach current `ID_CA`, `ID_PM`, `ID_SD`, and `SetupGameLevel` lookups. | Prevent more hard-coded Wolf-specific archive indices while preserving licensed-data separation. Identity drift can break saves and legacy lookup. | Manifest validation and unchanged owned-data compatibility. | +| R1 | Optional | Add read-only diagnostics beside current CA/PM lookup diagnostics. | Useful for failures, but it must not become a second loader. | Deterministic textual output. | +| R2 | **Required** | Place one validated catalog/image-view boundary in front of `PM_GetPage`, Classic `CastRay`/scalers, Enhanced `WL_RenderRayWorld`, and sprite/HUD/weapon consumers. Keep a legacy adapter. | Enables 64 and 128 dimensions without split content systems. Risks are Classic pixel drift, overflow, opacity, pivot/scale, and cache lifetime. | Legacy hashes first, then 128/malformed/failure tests and both-renderer integration. | +| R2 | Deferred | Leave PNG decoding policy, true-colour pipeline, filtering, atlases, and GPU ownership outside the dimension-safe indexed descriptor revision. | None is required to remove fixed-dimension assumptions safely. | Later approved contract. | +| R3 | **Required** | Bind new `WL_AGENT`/`WL_ACT*`/`WL_COMBAT` weapons, enemies, items, and sound/image references to stable content IDs and descriptors rather than raw page/cache values. | Simulation ordering and save compatibility must remain deterministic. | Fixed-tick gameplay, save compatibility, and missing-resource failure tests. | +| R3 | Optional | Pass small read-only views into isolated actor/combat logic only where tests show globals block the selected feature. | A premature comprehensive context can merely hide globals and widen the diff. | Focused parity tests for each extraction. | +| R4 | **Required** | Add one SDL-free authored-world owner and make a session builder the seam into `SetupGameLevel`, `tilemap`, `actorat`, doors, statics, and actor spawn helpers. Workshop controller uses transaction/query APIs only. | Durable definitions must not alias live visibility, actor, door, or pushwall state; edits must be atomic. | Complete headless edit, validation, failure, history, legacy-import, and session-build suite. | +| R4 | Optional | Replace further direct global readers only after the session builder is proven. | Broad migration increases regression surface without enabling Workshop operations. | Per-extraction deterministic regression. | +| R5 | **Required** | Keep Workshop selection/overlay/input in its controller/presentation modules; render immutable world queries and send changes through the R4 transaction API rather than `sdl_input` or UI callbacks mutating cells. | Prevent UI state from becoming the content source of truth. | Headless world tests plus SDL interaction/presentation tests. | +| R5 | Optional | Batch bounded paint/fill gestures into one world transaction. | Large deltas can exceed history limits or partially fail if not planned first. | Boundary, allocation-failure, cancel, and one-step undo tests. | +| R6 | **Required** | Add versioned `world_encode`/`world_decode`, a platform atomic-file adapter patterned after `save_file.c`, and a playtest session built from an isolated validated snapshot before entering `DemoLoop`/game state. | Prevent partial writes, silent format drift, and aliasing between live playtest and edit/history state. | Fault-injected persistence, deterministic round trip, malformed input, and end-to-end playtest/return gates. | +| R6 | Deferred | Concurrent editing, unbounded history, scripting, ECS/scene graph, multistorey geometry, and renderer replacement. | No accepted requirement justifies their cost. | New approved revision only. | + +Across all milestones, wholesale replacement of `gamestate`, actor pools, and +render globals is deferred. Extraction is justified only when a selected +revision needs a testable seam and has parity evidence. + +## Automation opportunities + +The playbook now records the source/include/global inventory that recurred in +R0.1 and R0.2. AUTO-12 proposes a future sorted inventory and SDL-boundary +allow-list check, with golden and failure tests, after R0.3 establishes the +test-helper conventions. It intentionally will not infer semantic ownership; +allocation, mutation, callback, and teardown traces still require review. + +No script is added in this revision. The current procedure is short, +read-only, produces an ignored evidence log, and avoids creating a second +validation framework before R0.6. + +## Compatibility risks and mitigations + +| Risk | Classic | Enhanced | Required mitigation | +|---|---|---|---| +| Texture-coordinate generalization | Integer masks/columns can change historical pixels. | Different rounding can create seams or disagreement with Classic. | Preserve and hash the legacy 64x64 path; specify fixed-point rounding before adding 128. | +| Resource opacity/pivot/scale | Legacy sprites encode assumptions in decode/scaler behavior. | Wide render can expose pivot or scale disagreement. | Make metadata explicit; adapt legacy values exactly; test zero-index opacity cases. | +| Render-side mutation | `spotvis`, actor visibility/activation, and bonus pickup currently occur during Classic refresh. | Snapshot render is read-only by design. | Freeze behavior in R0.3; later move gameplay mutation to simulation only under a dedicated revision with parity tests. | +| Snapshot/session conversion | Classic reads live globals. | Enhanced reads current/previous snapshots. | Build both from the same validated session and test at identical fixed ticks. | +| Simulation scheduling | Architectural changes can accidentally add UI/render-time simulation or alter catch-up behavior. | The same risk applies when snapshot capture/interpolation boundaries move. | Preserve `GameStep`'s 70 Hz authority, bounded tic handling, and deterministic ordering; freeze traces in R0.3. | +| View/aspect ownership | Original framebuffer/HUD is fixed 4:3. | World target may be widescreen. | Keep UI composition and world target dimensions separate; validate both modes in R0.4. | +| Stable authored IDs | Current saves/runtime use bounded slots and pointers indirectly. | Presentation generations already distinguish reused actor slots. | Do not substitute authored IDs for runtime IDs silently; translate at session-build/save boundaries. | +| Shutdown order | Borrowed page/chunk pointers become invalid after cache shutdown. | SDL targets also have independent lifetime. | Catalog/world destructors own their data; render calls borrow only for documented scope; test partial teardown. | + +## Alternatives considered + +- **Edit the three legacy map planes directly:** rejected as the Workshop's + canonical model because doors, object IDs, metadata, validation, history, + and versioned authored content exceed those planes. Keep them as an import + adapter and compatibility source. +- **Use current runtime globals as the editor document:** rejected because + visibility, active actors, consumed statics, and moving doors/pushwalls are + session state. Undo and playtest isolation would be unreliable. +- **Introduce a comprehensive engine context now:** deferred. It would touch + nearly every subsystem before deterministic behavior is frozen. Small + explicit views/owners at needed seams have lower risk. +- **Give each renderer its own resource system:** rejected because it invites + dimension, opacity, and lifetime disagreement. One catalog with distinct + sampling/presentation remains compatible with both renderer designs. + +## Validation and acceptance evidence + +Evidence directory: `build/validation/R0.2/` (ignored by Git). + +| Criterion | State | Evidence | +|---|---|---| +| A05: dependency map matches inspected source | **PASS** | Direct include/symbol scans and manual lifecycle tracing are recorded in `architecture-inspection.log`; the diagrams and ownership table above use those observed edges. | +| A06: coupling and proposed extraction points are concrete | **PASS** | Tables identify declarations, owners, mutators, lifetimes, transaction boundary, session builder, catalog view, and per-revision verification. | +| A07: Classic/Enhanced compatibility risks are listed | **PASS** | Compatibility table covers sampling, opacity/scale, render mutation, snapshots, aspect, identities, and teardown. | + +Required validation for this documentation revision: + +1. Re-run the source inventory and SDL-boundary commands in the playbook. +2. Inspect each Mermaid edge against includes/calls and verify balanced fences. +3. Run the complete existing owned-data regression and record its exit status. +4. Confirm the diff contains documentation only, no tracked generated files, + and no third-party or protected data. + +Failure injection is a design obligation for R2/R4/R6, not executable R0.2 +coverage. Required cases are invalid dimensions/overflow and partial catalog +construction (R2), allocation/validation/conflict failures during atomic edit +commit (R4), and truncated input/write/replace failure (R6). + +Executed validation: + +| Check | Command | Result | +|---|---|---| +| Architecture/global inventory | Commands in the playbook's architecture inspection procedure | **PASS**, exit 0; 1,511 lines in `build/validation/R0.2/architecture-inspection.log`. | +| Existing regression | `python3 -m unittest discover -s tests -v` | **PASS**, exit 0; 153 tests in 108.627 s. Twenty-one legally owned WL6/DOS-data checks were skipped because `WOLF3D_DATA` and an owned DOS installation were unavailable. Log: `build/validation/R0.2/test-suite.log`; status: `test-status.txt`. | +| Owned-data compatibility subset | `WOLF3D_DATA=... python3 -m unittest discover -s tests -v` | **NOT RUN**; no owned-data path was available in this environment. R0.1 remains the latest recorded no-skip owned-data run. | +| Markdown/Mermaid source | Fence-count check plus manual review of every arrow against the source inventory | **PASS**; three balanced Mermaid blocks. Render-tool execution was **NOT RUN** because `mmdc` is not installed. | +| Patch whitespace | `git diff --check` | **PASS**, exit 0. | +| Scope and ignored content | `git status --short`, `git diff --name-only`, `git check-ignore -v 3rdparty 3rdparty/probe` | **PASS**; only the R0.2 report and playbook are changed, and `/3rdparty/` remains ignored by `.gitignore:27`. No runtime source, test, dependency, generated binary, or protected asset changed. | + +### Review checklist + +- [x] Current arrows and ownership claims trace to inspected source. +- [x] Authored content is separated from live simulation state. +- [x] Proposed interfaces are native C11, bounded, SDL-free, and explicit + about ownership and failure. +- [x] Classic and Enhanced risks and proof obligations are stated. +- [x] Work is assigned to milestones without claiming implementation. +- [x] No production code, dependencies, generated binaries, or protected + content are included. + +### Rollback + +This revision changes documentation only. Reverting its documentation commit +restores the previous roadmap state; there is no binary, format, asset, or +runtime migration to undo. + +## Handoff to R0.3 + +R0.3 should start by capturing deterministic behavior around current state, +not by implementing this proposed world interface. The first work item is an +SDL-free fixture/reset contract for a minimal enclosed level, logical controls, +and actor/door/pushwall state, followed by repeatable tick/query/ray assertions. +Run this exact inventory first, then create the R0.3 revision contract before +changing code: + +```sh +rg -n 'R0\.3|deterministic|fixture|reset|GameStep|SetupGameLevel|ShutdownGameLevel' \ + docs/milestones/R0 docs/validation tests src/engine +``` diff --git a/docs/milestones/R0/R0.3.md b/docs/milestones/R0/R0.3.md new file mode 100644 index 00000000..192f7b71 --- /dev/null +++ b/docs/milestones/R0/R0.3.md @@ -0,0 +1,248 @@ +# R0.3 Deterministic headless CPU harness evidence + +**Revision:** R0.3 + +**Branch:** `docs/revival-roadmap-and-validation` + +**Base commit:** `10ffb89` + +**Status:** PASS for A08, A09 and A10, with the limitations recorded below. + +**Scope:** tests and test documentation only; no production C, build, dependency +or asset changes. + +## Purpose + +Record the deterministic headless coverage that exists for the R0.3 contract: +fixed-step simulation, map boundaries and collision, restart/reset, fixed-seed +replay, presentation-rate determinism, and the Classic renderer side effects +that are currently observable from the test harness. Acceptance is judged from +commands actually run. Agent-executed results are kept separate from the full +regression result supplied by the user. + +## Revision contract + +### In scope + +- Deterministic synthetic fixtures and headless C test binaries. +- Explicit authoritative-state snapshots and field-by-field comparisons. +- Map-boundary, collision, restart, replay and presentation-schedule checks. +- Characterisation of the existing `ThreeDRefresh()` side effects. +- Evidence for A08, A09 and A10, including exact commands and results. + +### Out of scope + +- Production engine changes, renderer refactors or gameplay timing changes. +- R0.4 matched render baselines, R0.5 sanitizer/profiling work, and later + milestone tasks. +- Owned Wolfenstein WL6 data execution by the agent; those tests were skipped + locally and are only covered by the user-supplied full regression. +- SDL window, graphics-driver or human visual validation. + +## Deterministic headless testing implemented + +`tests/test_engine.py` compiles the engine core with the filesystem adapters +only; the synthetic `test_game_synthetic` path runs `game-tests` against +archives generated by `tests/game_fixtures.py`. No SDL window is created. The +C tests use the `CHECK` macro in `tests/game_tests.c`, which reports source +line, expression and `CA_Error()` on failure, giving actionable diagnostics +without a renderer. + +The fixture map is fixed: player spawn at tile `(2,2)`, one closed door at +`(6,2)`, perimeter walls, and no actors or statics at startup. All new tests +are gated by `argc == 2`, so they run only in synthetic fixture mode and never +in the commercial WL6 mode. + +## Coverage by area + +### Map boundary and collision + +`TestMapBounds()` resets actor/collision grids with `InitObjects()` and clears +`tilemap` to make a fully open 64x64 traversable region. It checks `TryMove()` +at both `MINDIST` edges on x and y, verifies that the opposite side is +rejected, and checks that `ClipMove()` refuses off-map movement instead of +sliding along an open axis. Because unrelated fixture tiles are removed, the +only possible obstruction is the coordinate bound under test. `GameStop()` +restores collision state through `ShutdownGameLevel()` and `InitObjects()`. + +`TestSimulation()` additionally covers fixed-step input behaviour: one +`GameStep(0)` does not move, `GameStep(1)` consumes a key press, a later +`GameStep(2)` with no input does not move, cleared keys do not move the player, +opposing turn inputs cancel, and a long-pause step is bounded like the +normal path. + +### Restart and reset + +`TestRestart()` uses `RunRestartCycle()` twice. Each cycle: + +1. Starts a synthetic game and captures a known initial snapshot: player + `(2*TILEGLOBAL+32768, 2*TILEGLOBAL+32768)`, tile `(2,2)`, angle `0`, + health `100`, ammo `8`, lives `3`, `TimeCount == 0`, one closed door. +2. Moves the player, then deliberately dirties actor reservation + (`actorat[10][10]`), `staticblock`, a map tile, door action/position and + pushwall state. +3. Calls `GameStop()`, asserts the map, actor, static and pushwall state are + cleared, starts a fresh game, and compares the snapshot with the initial + one. +4. Compares the result of two complete cycles. + +The snapshot is an explicit scalar projection (positions, counters, flags and +boolean grid occupancy); no raw pointer, padding or uninitialised byte is +hashed. + +### Deterministic replay and fixed seed + +`TestDeterministicReplay()` starts `GameStartMap(0, 0, 2, 42)` twice, each +time after a full `GameStop()` and `IN_ClearKeysDown()`. Both sessions replay +the same 61-tick logical input script through the shared `ReplayInputs()`: + +- hold `UpArrow` for 40 ticks to approach the closed door; +- release, then `Key(sc_Space)` to use the door; +- hold `UpArrow` for 10 ticks while the door opens; +- turn with `RightArrow`, then move again, and finish with an idle tick. + +Key-down/key-up events are balanced. `CaptureReplayState()` records player +position/tile/angle, `TimeCount`, health/ammo/lives/keys/score, episode/map/ +difficulty/weapon, `playstate`, actor and door counts, door coordinates/lock/ +orientation/action/position/tic-count/runtime tile, actor-grid occupancy at +the door, pushwall state, and player link/state null flags. +`CheckReplayStatesEqual()` compares these fields individually. + +### Presentation-rate determinism + +`TestPresentationRateDeterminism()` reuses the same seed, input script and +snapshot comparison. The only difference is presentation activity: + +- Session A: `WL_PresentCapture(t)` plus `WL_PresentSample(WL_TickNS(t), ...)` + after every one of the 61 ticks (61 captures). +- Session B: the same calls every fourth tick (15 captures). + +The capture counts are asserted, so the two schedules cannot silently become +identical. Presentation uses the existing read-only snapshot path; +`WL_PresentCapture()` copies authoritative state and `WL_PresentSample()` +writes only caller-owned storage. No extra Classic render call was added to +fake a different presentation rate. Both sessions end with identical +authoritative state after 61 simulation ticks. + +### Classic renderer side-effect characterisation + +`TestClassicRenderSideEffects()` calls the exact Classic rendering function +`ThreeDRefresh()` directly, not `WL_PresentSample()`. The deterministic setup +places the player at the west edge of tile `(3,2)`, spawns a visible actor at +`(4,2)`, a hidden actor at `(10,10)`, and places a `bo_clip` bonus at `(3,2)`. +`spotvis` is cleared and actor visibility flags are seeded so the before state +is known. + +After `ThreeDRefresh()` the test asserts: + +- `spotvis[3][2]` and `spotvis[4][2]` are marked by ray traversal, while + `spotvis[10][10]` behind the closed door is not; +- the visible actor gains `FL_VISABLE` and becomes active; +- the hidden actor's stale `FL_VISABLE` flag is cleared; +- `DrawScaleds()` called `GetBonus()`: ammo changes from `8` to `16` and the + static's `shapenum` becomes `-1`. + +This is a characterisation of current behaviour. It would fail if any of +those side effects disappeared. It uses no timing waits, SDL window or owned +WL6 data. + +## Acceptance criteria + +| Criterion | Status | Evidence | +| --- | --- | --- | +| **A08** fixed inputs yield matching final state across multiple rendering rates | **PASS** | Agent-executed `TestDeterministicReplay()` and `TestPresentationRateDeterminism()` compare explicit authoritative fields after 61 identical 70 Hz ticks with 61 versus 15 presentation captures. The user-supplied full regression also includes the existing `test_presentation.py::PresentationTests.test_synthetic`, which compares save payloads across 60/75/90/120/144/165/180/240 FPS; the agent did not re-run that file separately. | +| **A09** deterministic fixtures and failure diagnostics committed | **PASS** | `tests/game_fixtures.py` provides synthetic archives; `CHECK` in `tests/game_tests.c` reports line, expression and `CA_Error()`; the test tree was clean at commit `10ffb89` before this evidence file was added. All focused runs below exited zero. | +| **A10** no gameplay timing changes introduced as a side effect | **PASS** | No production C was changed. `TestSimulation()` exercises `GameStep(0/1/2)`, cleared input, opposing turns and bounded long-pause stepping; the replay presentation test advances only through the same 61 sequential `GameStep()` calls in both sessions. The user-supplied full regression reported no failures or errors. | + +## Validation evidence + +### Agent-executed validation + +Final focused run after the last test change: + +```sh +python3 -m unittest discover -s tests -p test_engine.py -k test_game_synthetic -v +``` + +Result: + +- Exit code: `0` +- `Ran 1 test in 12.552s` +- `OK` +- Harness output: `Original map/VSWAP, fixed-point ray/scaler, movement and menu/game tests passed.` + +The same command was also run after each R0.3 test increment; all final +incremental results were exit `0`, one test, `OK`: + +| Increment | Duration | +| --- | --- | +| `TestMapBounds()` isolation | `12.457s` | +| `TestRestart()` added | `11.898s` | +| `TestRestart()` synthetic-mode gating | `12.619s` | +| `TestDeterministicReplay()` added | `12.391s` | +| `TestPresentationRateDeterminism()` added | `12.733s` | +| `TestClassicRenderSideEffects()` added | `12.552s` | + +One intermediate run failed while developing the replay test because the test +incorrectly assumed a door tile was stored in `actorat`; the assertion was +corrected before the passing runs above. No production code was changed. + +Whitespace check, run by the agent after adding this document: + +```sh +git diff --check +``` + +Result recorded below in the handoff section. + +### User-supplied full regression + +The following result was supplied by the user and was **not** executed by the +agent for this revision: + +```sh +python3 -m unittest discover -s tests -v +``` + +Result as supplied: + +- `153 tests` +- `132 passed` +- `21 skipped` +- `0 failures/errors` +- `108.734 seconds` + +The user stated that the skipped tests require owned Wolfenstein data or +installations. No additional validation is claimed here. + +## Remaining limitations + +- 21 skipped tests were not executed by the agent; they require owned + Wolfenstein data or external installations. +- No SDL window, graphics driver, owned WL6 oracle run, sanitizer or profiler + was exercised in this revision. +- The presentation-rate test varies snapshot capture frequency over identical + 70 Hz simulation ticks; it is not a full Classic renderer-at-different-refresh + pixel comparison. The cross-FPS save comparison comes from the existing + presentation suite included in the user-supplied full regression. +- The Classic side-effect test covers `spotvis`, `FL_VISABLE` and `GetBonus()` + only. It does not cover `TransformActor()` view fields, the too-close actor + branch, `ThreeDRefreshPaused()` suppression, or pixel baselines; those belong + to later work such as R0.4. +- A08/A10 conclusions depend on the supplied full regression for the + existing 60-240 FPS presentation suite; the agent personally ran only the + focused synthetic command. + +## Handoff + +- **Current state:** R0.3 evidence documented and committed as `043884e`; + tests and production code were unchanged by the evidence revision. +- **Branch / base commit:** `docs/revival-roadmap-and-validation` / `10ffb89`. +- **Report commit / remote:** `043884e`, pushed to + `origin/docs/revival-roadmap-and-validation`. +- **Files changed by this revision:** `docs/milestones/R0/R0.3.md`. +- **Whitespace check:** `git diff --check` — exit `0`, no output. +- **Outstanding blockers:** owned-data and graphics validation remain + environment-dependent and are recorded as skipped, not passed. +- **Next command to reproduce the focused evidence:** + `python3 -m unittest discover -s tests -p test_engine.py -k test_game_synthetic -v` diff --git a/docs/milestones/R0/R0.4.1.md b/docs/milestones/R0/R0.4.1.md new file mode 100644 index 00000000..d3d283bd --- /dev/null +++ b/docs/milestones/R0/R0.4.1.md @@ -0,0 +1,328 @@ +# R0.4.1 Graphics baseline inventory + +**Revision:** R0.4.1 + +**Branch:** `docs/revival-roadmap-and-validation` + +**Inspected commit:** `043884e` + +**Status:** inventory complete; R0.4 acceptance criteria A11-A13 are **NOT RUN** + +**Scope:** documentation and source inspection only. No capture tool, renderer, +test, dependency, fixture, asset, or baseline image was added or changed. + +## Objective and boundary + +Audit the graphics capture and comparison facilities already present for the +Classic 4:3 and Enhanced widescreen paths, then define the smallest reproducible +R0.4 implementation. Existing facilities are labelled **EXISTS** below. +Unimplemented recommendations are labelled **PROPOSED**. + +This inventory does not establish an R0.4 baseline, perform human visual +approval, or satisfy A11-A13. It does not implement R0.4.2. + +## Rendering and capture paths that exist + +### Production paths + +| Capability | Status | Source and observed behavior | +|---|---|---| +| Classic indexed source | **EXISTS** | `src/engine/ID_VL.c/.h` owns the 320x200 indexed `framebuffer` and 256-entry VGA palette. `WL_DRAW.c`/`WL_SCALE.c` draw the Classic world, sprites, HUD, and weapon into it. | +| Enhanced indexed target | **EXISTS** | `src/engine/WL_RENDER.c/.h` renders a world snapshot into caller-owned `wl_render_target` storage. `WL_RENDER_TARGET.c/.h` bounds width, height, stride, capacity, and pixel writes. | +| Aspect calculation | **EXISTS** | `src/engine/WL_ASPECT.c/.h` fits explicit ratios. `src/platform/display_settings.h` defines Auto, 4:3, 16:9, 16:10, 21:9, and 32:9 plus Classic/Enhanced, internal render size, integer/fit, filter, smoothing, window, drawable, and fullscreen settings. | +| Immutable scene sampling | **EXISTS** | `src/engine/WL_PRESENT.c/.h` captures and interpolates previous/current camera, actor, door, static, tile, pushwall, weapon, and death state for Enhanced presentation. | +| SDL composition | **EXISTS** | `src/platform/sdl_video.c::VL_DrawScreen` converts indexed pixels through the active palette, uploads the Classic texture or Enhanced texture, applies the logical presentation, and renders it. `VW_UpdateScreen` presents it. | +| Named-path capture | **EXISTS** | `src/platform/sdl_video.c::VL_Capture(path)` redraws, calls `SDL_RenderReadPixels`, and writes BMP through `SDL_SaveBMP`. It captures the composed renderer result, not the raw indexed buffer. | +| User screenshot | **EXISTS** | `VL_Screenshot()` writes collision-resistant `screenshot--.bmp` files beneath SDL's `wolf3d-revive` preference path. F12 invokes it. Names are intentionally time-dependent. | +| CLI single capture | **EXISTS** | `src/main.c` accepts `--capture local.bmp` with a windowed run and restores the prior palette after capture. `--frames N`, `--menu`, `--level`, and `--no-audio` exist, but there are no CLI flags selecting renderer, internal resolution, aspect, filter, or a named deterministic gameplay scene. | + +`VL_Capture()` has an important boundary: SDL renderer readback follows the +active logical presentation. `tests/video_tests.c` verifies that after a +1000x600 Classic resize the saved BMP is the 800x600 logical viewport, not the +full drawable with its 100-pixel side bars. Tests that need the complete output +and black bars, such as `tests/display_tests.c::Geometry`, temporarily disable +logical presentation and call `SDL_RenderReadPixels` directly. A baseline must +state whether it represents logical content or the complete drawable; the two +are not interchangeable. + +The CLI capture occurs before the main presentation loop. It is useful for +startup/signon diagnostics (`tests/test_signon.py`) but is not presently a +general fixed-tick scene capture interface. Its result can also inherit the +configuration in the SDL preference directory unless the caller isolates +`XDG_DATA_HOME` and supplies known configuration. + +### Test harness capture entry points + +| Entry point | Status | What it already captures or checks | +|---|---|---| +| `tests/render_tests.c`, driven by `tests/test_render.py` | **EXISTS** | Direct Enhanced indexed targets, SDL output, three fixed internal sizes, Auto scaling, all explicit aspects, view sizes, HUD composition, wide geometry, sprite ordering/transparency, wall occlusion, weapon position, death phases, settings persistence, screenshots, and failure recovery. Uses synthetic `finale_files()` by default. | +| `tests/display_tests.c`, driven by `tests/test_display.py` | **EXISTS** | Full-output SDL readback for black bars and exact colors, window/drawable geometry, integer and fit scaling, presets, manual resize, fullscreen transitions, Classic/Enhanced switching, Auto and explicit aspects, and transition isolation. Optional `WOLF3D_CAPTURE_DIR` writes `display-settings.bmp`. | +| `tests/presentation_tests.c`, driven by `tests/test_presentation.py` | **EXISTS** | Immutable/interpolated snapshots, direct Enhanced image hashes for camera, door, and pushwall interpolation, and identical saves across 60/75/90/120/144/165/180/240 FPS. It proves images differ at intermediate states but does not compare them to committed graphics baselines. | +| `tests/classic_tests.c`, driven by `tests/test_classic.py` | **EXISTS** | All 16 Classic view sizes, projection and border geometry, sprite/HUD clipping, framebuffer determinism, demos, and two optional named BMP captures under `WOLF3D_CAPTURE_DIR`. | +| `tests/video_tests.c`, built by `tests/test_engine.py` | **EXISTS** | Exact palette conversion, nearest colors, Classic 4:3 logical geometry, resize behavior, palette-only upload, capture dimensions, device failure, and repeated video lifecycle. | +| `tests/test_signon.py` plus `tests/signon_tests.c` | **EXISTS** | Parses CLI BMP bytes without an image dependency and exactly verifies known synthetic pixels/palette scaling. Also exercises direct capture and renderer readback. | +| `tests/campaign_sdl_tests.c` | **EXISTS** | Optional named captures for menus, a pushwall before/moving/open, intermission, and next floor. The Python runner does not make these R0.4 baselines. | +| Other SDL harnesses | **EXISTS** | Boss, finale, controls, loading, menus, and save harnesses already accept a directory or `WOLF3D_CAPTURE_DIR` and call `VL_Capture`. These are useful scene sources but currently have no shared manifest or comparison policy. | +| `tests/presentation_benchmark.c` | **EXISTS** | Optional `M8_CAPTURE` BMPs at several render sizes. It is a benchmark harness, so its captures should not become correctness baselines without freezing scene/timing inputs separately. | + +No capture wrapper corresponding to the proposed +`tools/capture_baseline.sh` exists. `docs/automation/PLAYBOOK.md` correctly +lists AUTO-06 as not implemented. + +## Existing comparison coverage + +### Exact checks already available + +- **Classic source pixels:** `tests/render_original_tests.c` and + `tests/render_native_hashes.c` produce exact framebuffer hashes compared by + `tests/test_render.py` with committed CSV files. These require the expected + legally owned WL6 revision and skip otherwise. +- **Synthetic Classic SDL output:** `tests/test_signon.py` reads BMP headers, + normalizes row direction/stride, and checks scaled pixels against the + generated indexed source and original palette without an imaging library. +- **Enhanced CPU output:** `tests/render_tests.c` performs exact indexed pixel, + memory-guard, repeated-image hash, HUD, aspect, sprite, opacity, weapon, and + wall-occlusion assertions. +- **Classic versus wide geometry:** `render_tests.c::Wide` checks that central + world pixels and HUD content agree exactly while widescreen adds rays rather + than stretching the Classic scene. +- **SDL software output:** `render_tests.c::AutoScaling` compares a captured + synthetic 4K nearest-neighbor image pixel-for-pixel with a directly rendered + 1920x1080 indexed target when the dummy backend supplies exact 3840x2160 + output. +- **Window composition:** `display_tests.c::Geometry` disables logical + clipping, reads the full output, and checks black bars, red/green halves, + fit/integer geometry, and drawable dimensions. +- **Presentation interpolation:** `presentation_tests.c::Images` hashes direct + indexed render targets and proves camera/door/pushwall intermediate images + are distinct and independent from later mutations of the live world. + +### What does not yet exist + +- No committed synthetic Classic and Enhanced image set representing the same + named scene, camera, tick, palette, view size, and content identity. +- No baseline manifest or sidecar metadata schema. +- No single command selects scenes, renderer modes, output sizes, aspects, and + evidence directory with a bounded result summary. +- No generic image comparator reports changed-pixel count, bounding box, + channel error, masked regions, or an explanatory diff image. +- Existing screenshot tests usually verify file count/signature or exact + hand-picked pixels; saved BMPs are not broadly compared with goldens. +- `WOLF3D_CAPTURE_DIR`, `M8_CAPTURE`, F12, and CLI `--capture` are separate + opt-in surfaces with different naming and scene timing. +- Fullscreen checks under the dummy driver test state transitions, not a + physical monitor, compositor, DPI, HDR, or exclusive-mode result. +- Linear filtering and hardware renderer output are not portable pixel-exact + oracles. Existing exact output checks deliberately use the SDL software + renderer and nearest filtering. +- Captures do not embed or accompany commit, fixture, driver, renderer, + dimensions, aspect, palette, tick, camera, or tolerance metadata. +- The existing owned-data hash oracles cannot be redistributed as commercial + screenshots and do not provide a synthetic public visual baseline. + +## Synthetic assets and scene control + +`tests/game_fixtures.py` builds project-generated map, VSWAP, graphics, UI, +sprite, and campaign/finale inputs in temporary directories. `finale_files()` +is already used by all three principal graphics suites. These fixtures require +no commercial data and are removed after each Python test. + +The fixture art is diagnostic rather than aesthetic: deterministic palette +indices, simple posts, flat pictures, and bounded maps make exact sampling and +occlusion visible. This is suitable for public regression baselines. Owned WL6 +checks remain a separate private compatibility layer and must not produce +committed screenshots. + +Current scene construction is distributed across harness functions. The most +reusable existing scene ingredients are: + +- `render_tests.c::Visual`: near/far statics, ordering, explicit opacity, + opaque palette index zero, wall occlusion, and weapon placement; +- `presentation_tests.c::Images`: fixed camera plus closed/opening door and + moving pushwall interpolation; +- `classic_tests.c::Views` and `Border`: all Classic view sizes and + near-sprite/wall/HUD clipping; +- `campaign_sdl_tests.c`: before/moving/open pushwall states; +- `render_tests.c::DeathContinuity`: fixed death phases across three render + sizes and all five explicit aspects plus Auto. + +## Proposed reproducible baseline scenes + +The following scenes are **PROPOSED**. They reuse those ingredients and do not +require a second scene model. + +| ID | Deterministic setup | Required observations | +|---|---|---| +| `corridor-static` | Synthetic level, fixed seed/tick, player at a recorded tile center and cardinal angle, view size 15, closed door ahead, near and far statics, one actor, fixed HUD/weapon state. | Wall columns, closed-door clipping, sprite depth/order, weapon and complete HUD. Capture from both Classic and Enhanced at the same authoritative state. | +| `door-motion` | Same camera and content with door positions 0, 32768, and 65535 from explicit snapshots. | Leading edge, revealed wall/sprite, depth, and interpolation. Directly reuse the door setup in `presentation_tests.c::Images`. | +| `pushwall-motion` | Fixed pushwall at start, half-tile, and crossing boundary with a sprite behind it. | Pushwall texture coordinate, occupied/revealed cells, occlusion, and snapshot continuity. Reuse presentation/campaign setup. | +| `edge-clipping` | Classic minimum and maximum view sizes with a near sprite straddling each viewport edge and a tall wall/post; unchanged HUD. | No draw outside the Classic bevel, consistent Enhanced target bounds, sprite/wall clipping, and HUD isolation. Reuse `classic_tests.c::Border`. | +| `display-transition` | One frozen `corridor-static` state shown after a manual non-integer resize and after fullscreen/windowed restoration. | Full drawable geometry, black bars, logical rectangle, no simulation/RNG advance, and unchanged logical scene pixels. Reuse `display_tests.c`. Physical fullscreen remains a manual platform gate. | + +Death/fizzle, menus, finales, and every Classic view size remain covered by +existing assertions. They need not all become first-slice image goldens. Add a +baseline only when an image materially improves the current scalar/pixel +checks. + +## Proposed resolution and aspect matrix + +Internal render size, logical gameplay aspect, and final drawable size are +independent settings and must be recorded separately. + +### Automated required matrix + +| Renderer | Internal source/target | Gameplay aspect | Drawable/window | Purpose | +|---|---:|---:|---:|---| +| Classic | 320x200 indexed; 320x240 corrected logical canvas | 4:3 | 640x480 | Small exact nearest/software reference. | +| Classic | same | 4:3 | 1280x720 | Centered 4:3 content and side-bar/full-output geometry. | +| Classic | same | 4:3 | 1001x601 | Non-integer fit and edge-rounding reference. | +| Enhanced | 640x480 | 4:3 | 640x480 | Small target and Classic-comparable framing. | +| Enhanced | 1280x720 | 16:9 | 1280x720 | Primary widescreen reference. | +| Enhanced | 1280x720 | 16:10 | 960x600 or 1280x800 | Explicit aspect fit and HUD centering. | +| Enhanced | 1280x720 | 21:9 | 1680x720 | Ultrawide ray extension and clipping. | +| Enhanced | 1280x720 | 32:9 | 2560x720 | Maximum supported aspect boundary. | +| Enhanced Auto | resolved target recorded | Auto | 1001x601 | Real output-derived aspect and non-integer dimensions. | + +The existing 1920x1080 fixed target and Auto-derived 1920x1080, 1920x803, +and 1920x540 targets should remain assertion coverage. A 1920x1080 capture can +be included for the primary scene, but duplicating every scene at every +resolution is not necessary for the first baseline. + +### Manual/platform matrix + +- Native Linux software renderer at the primary Classic and Enhanced modes. +- Native Linux default accelerated renderer at the same modes, visually + inspected but not assumed pixel-identical to software. +- Fullscreen enter/exit and restored window size on a physical display. +- Windows/Wine capture only when the R0.4 contract selects it; Wine/dummy is + not evidence of physical Windows display behavior. +- High-DPI or non-1x drawable scaling is **NOT RUN** unless such hardware or a + verified backend is available. + +## Proposed capture metadata + +Every baseline/candidate pair should have a machine-readable record containing: + +- schema version, scene ID, baseline role, repository commit, dirty-tree flag, + exact command, exit code, and capture timestamp; +- fixture generator and content identity/hash; explicit statement that inputs + are synthetic or private (private captures never committed); +- Classic/Enhanced mode, view size, authoritative tick and RNG index, camera + position/angle, relevant door/pushwall/actor/static state, weapon/frame, and + palette identity; +- internal indexed width/height/stride, requested aspect and resolved aspect, + fitted scene/UI rectangles, logical presentation size, window point size, + drawable pixel size, and pixel density when available; +- fullscreen/windowed, integer/fit, Auto/fixed resolution, nearest/linear, + smooth interpolation, VSync, and presentation sample time; +- OS/architecture, compiler, SDL version, SDL video driver, render driver or + renderer name, pixel format, and capture method (`indexed-target`, + `logical-VL_Capture`, or `full-output-readback`); +- image width/height/format, normalized pixel hash, baseline hash, comparison + policy/version, changed-pixel metrics, and evidence paths; +- manual reviewer, date, result, and notes where visual approval is required. + +The metadata must be written beside ignored run evidence even when the baseline +image itself is later approved for source control. A BMP filename alone is not +reproducibility evidence. + +## Proposed comparison policy + +1. **Exact indexed comparisons:** Classic 320x200 framebuffer and Enhanced + CPU `wl_render_target` output from synthetic fixtures must compare every + indexed pixel exactly. Store/hash canonical row-major pixels, not structure + padding or pointers. +2. **Exact canonical SDL profile:** SDL software renderer, nearest filtering, + fixed palette, fixed drawable, and fixed logical rectangle may compare + normalized RGBA pixels exactly. Normalize BMP row direction, padding, and + header fields before hashing. `tests/test_signon.py` already demonstrates a + dependency-free BMP reader. +3. **Full-output geometry:** use direct full renderer readback, not + `VL_Capture`, when black bars and drawable edges are part of the assertion. + Record the logical rectangle and compare bars separately from content. +4. **Linear/accelerated/platform output:** do not apply an unexplained global + tolerance. First compare deterministic geometry and the indexed source. + If R0.4.2 finds real backend variance, define a named profile with measured + per-channel maximum, changed-pixel budget, excluded edge mask, and a diff + image. Keep human visual review mandatory. +5. **Interpolation and animation:** freeze the authoritative tick and exact + sample timestamp/alpha. Otherwise a legitimate sub-tick difference is not a + renderer regression. +6. **Palette conversion:** synthetic nearest/software output should retain the + existing exact VGA expansion `(value << 2) | (value >> 4)`. Do not hide + palette changes behind perceptual tolerance. + +No tolerance value is asserted by this inventory because no candidate/baseline +variance set was measured in R0.4.1. + +## Proposed acceptance tests for R0.4 + +| Criterion | Current state | Proposed passing evidence | +|---|---|---| +| **A11: baseline images and capture metadata reproducible** | **NOT RUN** | A clean checkout executes one documented bounded command against synthetic fixtures; every required scene/mode produces normalized pixels plus complete metadata; a second run at the same commit/profile has identical canonical hashes; missing SDL/data/output prerequisites fail nonzero and are reported. | +| **A12: all required modes visually inspected** | **NOT RUN** | Named reviewer records PASS/FAIL for every required Classic/Enhanced scene and the automated matrix, plus native software/accelerated and physical fullscreen gates that the environment supports. Unsupported physical/high-DPI platforms remain NOT RUN, never implied by dummy SDL. | +| **A13: comparisons distinguish variance from regressions** | **NOT RUN** | Tests prove that an unchanged run passes, a controlled pixel/geometry mutation fails with location/metrics, dimension or metadata mismatch fails, exact indexed and canonical software profiles use zero tolerance, and any measured platform-tolerant profile accepts only its documented bounded variance. | + +## Smallest practical R0.4.2 implementation + +1. Extend `tests/render_tests.c` and its existing Python driver rather than add + a new renderer or scene model. Give the existing synthetic `Visual`, door, + and pushwall setups stable scene IDs and an opt-in evidence directory. +2. Emit canonical indexed pixels for Classic and Enhanced at the same frozen + state. Add final SDL captures only for the small output matrix where + composition itself is under test. +3. Reuse `VL_Capture` for logical-content BMPs and the already proven direct + full-output readback pattern from `display_tests.c` for bars/drawable + geometry. Do not change production capture behavior merely for tests. +4. Have the existing Python unittest write/read a small versioned manifest, + normalize pixels, compare exact profiles, and report dimensions, changed + pixel count, bounding box, and hashes. Use only the Python standard library + or existing SDL C path; add no imaging dependency. +5. Keep approved redistributable synthetic goldens small. Store ordinary run + captures, diffs, logs, and private owned-data images under ignored + `build/validation/R0.4/`. +6. Run the focused graphics suites, complete regression, and manual visual + checklist before assigning PASS to A11-A13. Wrapper/CI orchestration remains + R0.6 work. + +This sequence adds evidence plumbing around facilities that already exist. It +does not require renderer refactoring, a new capture executable, or a general +image-processing framework. + +## Validation and review checklist + +R0.4.1 validation is documentation-only: + +- [x] R0.3 report commit/push statement corrected to `043884e` without + altering its validation results or A08-A10 states. +- [x] Principal Python graphics drivers and their C harnesses inspected. +- [x] Production CLI, F12, `VL_Capture`, logical presentation, and full-output + readback behavior traced in source. +- [x] Existing versus proposed behavior labelled explicitly. +- [x] No production C, test, dependency, fixture, asset, or `3rdparty/` file + changed. +- [ ] A11-A13 execution and visual review — **NOT RUN**, assigned to later + R0.4 revisions. + +Required command: + +```sh +git diff --check +``` + +Executed after the final documentation edit: **PASS**, exit `0`, no output. +The new untracked report was also checked as a new-file diff and contained no +whitespace errors. `git status --short -- src tests 3rdparty third_party` +returned no changes. + +Rollback is deletion of this inventory plus reversion of the one factual R0.3 +handoff correction. No runtime, format, dependency, baseline, or user-data +migration is involved. + +## R0.4.2 handoff + +Do not begin implementation until this inventory is reviewed. The first task +is to freeze `corridor-static` in the existing render harness and emit paired +Classic/Enhanced canonical indexed buffers with a minimal versioned metadata +record. Prove same-profile repeatability and controlled-mismatch diagnostics +before adding the wider capture matrix. diff --git a/docs/milestones/R0/R0.4.md b/docs/milestones/R0/R0.4.md new file mode 100644 index 00000000..9896af8a --- /dev/null +++ b/docs/milestones/R0/R0.4.md @@ -0,0 +1,296 @@ +# R0.4 matched graphics baseline evidence + +**Revision:** R0.4 + +**Branch:** `docs/revival-roadmap-and-validation` + +**Reviewed commit:** `533c8e9` + +**Baseline schema/source revision:** `1` / `R0.4-baseline-v1` + +**Status:** **PASS for the reviewed synthetic graphics baseline scope**. The project owner visually inspected the generated captures on 2026-11-22 and reported that they looked fine. Untested physical display and platform configurations remain NOT RUN. + +## Purpose and scope + +R0.4 adds a deterministic, synthetic visual regression baseline for the +existing Classic 4:3 and Enhanced widescreen renderers. It uses the established +`tests/render_tests.c` executable, Python unittest driver and synthetic archive +generator. No production source, renderer architecture, gameplay timing, save +format, dependency, commercial asset or `3rdparty/` content changed. + +The baseline protects canonical indexed pixels. Existing SDL dummy/software +tests continue to protect palette conversion, logical presentation, black bars, +resize/fullscreen transitions and exact output where that backend is stable. +Accelerated, physical-fullscreen and high-DPI output are not treated as +pixel-identical to the canonical baseline. + +## Baseline integrity correction + +Review of commit `533c8e9` found that `validate_manifest()` popped each +candidate `pixel_hash` and skipped all archive reads when it matched the locked +manifest hash. A missing, extra or corrupted archived baseline could therefore +remain undetected while the synthetic candidate still matched the manifest. +This correction changes only test helpers, negative tests and evidence: + +- The archive name list is checked as an exact set of `.w3i` + entries against the manifest, with duplicate and non-capture entries rejected. +- Every archived capture is read, parsed and checked for manifest dimensions + and SHA-256 before any candidate comparison, even when the candidate hash is + identical. +- The candidate is still compared with the validated archived pixels using + exact `compare_pixels()`; `changed_pixels` and inclusive `bounding_box` + diagnostics remain on every pixel/hash failure. +- Two end-to-end `validate_manifest()` negative tests now prove that a missing + archive entry and a one-pixel archive corruption fail while candidate hashes + match. They do not call the comparator helpers directly. + +No production C, capture scene, renderer behaviour, palette or baseline image +changed. A12 remains **NOT RUN**. + +## Implemented functionality + +- `tests/render_tests.c` freezes one shared synthetic world and emits a bounded + `w3r-indexed-v1` format: 16-byte magic/version/width/height header followed by + exactly one palette index per pixel. +- The shared scene fixes seed `0`, tick `0`, camera tile `(2,3)` plus half-tile + offsets, angle `0`, view size `15`, pistol state, map geometry and palette. + It contains corridor walls, a door, near/far statics, an actor, HUD and weapon. +- Classic captures retain the authoritative 320x200 framebuffer. Output + captures apply deterministic nearest-neighbour 320x200-to-corrected-4:3 + presentation with centered black letterboxing. +- Enhanced captures use the existing `WL_RenderFrameAspect` and caller-owned + indexed targets; no new rendering path was introduced. +- `tests/visual_baseline.py` validates the archive capture ID set, parses every + archived capture, checks its dimensions and SHA-256 against the manifest, + compares all metadata, performs exact indexed candidate comparisons, reports + changed-pixel counts and inclusive difference bounding boxes, and writes + palette-correct 8-bit BMPs with only Python's standard library. +- `tests/fixtures/visual_baselines.json` locks metadata and hashes. + `tests/fixtures/visual_baselines.zip` deterministically stores the 32 exact + synthetic indexed baselines (18,976,516 bytes uncompressed; about 1.2 MB + committed) so a regression can produce spatial diagnostics rather than only + a hash failure. +- `tests/test_render.py` generates and validates the baseline on every synthetic + render run. It proves exact equality, deliberate one-pixel failure, dimension + failure and metadata failure, plus end-to-end rejection of a missing archive + entry and corrupted archived pixels. The synthetic gate cannot skip when + owned Wolfenstein data is absent. +- Generated captures, BMPs, manifests and logs remain under ignored + `build/validation/R0.4/`. + +Classic rendering still calls the existing paused gameplay renderer. No +`spotvis`, `FL_VISABLE`, `GetBonus()` or other observable Classic behavior was +moved or removed; the R0.3 characterization remains intact. Simulation remains +70 Hz. + +## Capture scenes and matrix + +There are 32 committed baseline entries: 15 Classic and 17 Enhanced. + +| Scene | Frozen states | Baseline coverage | +| --- | --- | --- | +| `corridor-static` | one static state | Paired Classic 320x200 and Enhanced 1280x720; Classic outputs 640x480, letterboxed 1280x720 and 1001x601; Enhanced 640x480 4:3, 1280x720 16:9, 1280x800 16:10, 1680x720 21:9, 2560x720 32:9 and 1001x601 Auto | +| `door-motion` | closed `0`, half-open `32768`, open `65535` | Classic 320x200 and Enhanced 1280x720 16:9 for every state | +| `pushwall-motion` | initial `(state 1, position 0)`, moving `(64,32)`, tile boundary `(128,0)` | Classic 320x200 and Enhanced 1280x720 16:9 for every state | +| `edge-clipping` | statics at the corridor's upper/lower viewport edges | Classic 320x200 and Enhanced 1280x720 16:9 | +| `display-transition` | initial, letterbox/wide, nonstandard resize/Auto, restored | Classic 640x480, 1280x720, 1001x601 and restored 640x480; Enhanced 640x480 4:3, 1280x720 16:9, 1001x601 Auto and restored 640x480 | + +The restored Classic and Enhanced hashes are asserted equal to their respective +initial hashes. Actual SDL display state restoration, logical rectangles and +black bars remain covered by `test_display.py`; the indexed display-transition +captures make the corresponding visual states reviewable. + +## Manifest contract + +The JSON root contains `schema_version` and a sorted `captures` array. Each +capture records: + +- stable capture ID and scene ID; +- rendering mode and named state; +- synthetic fixture SHA-256 identity and semantic source revision; +- authoritative tick, fixed seed, camera, view, weapon and relevant door or + pushwall state; +- internal and output dimensions plus selected aspect; +- palette identity, indexed format and SHA-256 pixel hash; +- capture method, SDL/backend applicability and comparison policy. + +`source_revision` is the versioned baseline contract +`R0.4-baseline-v1`, not a self-referential Git commit. The report records the +Git base and the final handoff supplies the commit containing the baseline. +Fixture and palette hashes bind the pixels to their actual generated inputs. + +## Comparison rules + +1. Canonical Classic and Enhanced indexed captures are exact. There is no + tolerance and no ignored region. +2. Header schema, dimensions, payload length, candidate/manifest capture ID set, + archive/manifest capture ID set and all metadata must match before pixels are + accepted. Duplicate or unexpected archive entries are rejected. +3. The archived pixels are always read and verified against the manifest's + `output_dimensions` and `pixel_hash`; candidate hash equality never bypasses + this check. The validated archived capture is then compared exactly with the + candidate. Any pixel or hash failure reports `changed_pixels`, the inclusive + `(min_x, min_y, max_x, max_y)` bounding box and both hashes. +4. Classic corrected output is deterministic nearest-neighbour indexed scaling + using the original six-bit palette identity. BMP review expansion uses + `(value << 2) | (value >> 4)`. +5. Existing dummy/software SDL exact comparisons remain exact. No arbitrary + tolerance is applied to accelerated, physical-fullscreen or high-DPI output; + those configurations require separate platform evidence and visual review. +6. An intentional baseline update requires `WOLF3D_UPDATE_BASELINES=1`, review + of both manifest/archive changes and retained BMPs, followed by an ordinary + validation run. The update flag is never part of the canonical command. + +## Validation interface + +Canonical synthetic graphics command: + +```sh +python3 -m unittest discover -s tests -p test_render.py -v +``` + +Review-capture command: + +```sh +WOLF3D_BASELINE_DIR="$PWD/build/validation/R0.4/captures" \ + python3 -m unittest discover -s tests -p test_render.py -v +``` + +The canonical command reports unittest progress, build failures, owned-data +skips and comparison diagnostics, and exits nonzero on a required synthetic +regression. Callers should apply an external timeout until R0.6 supplies the +common bounded runner. The retained-capture command produced 32 `.w3i`, 32 BMP +and one run manifest in this validation. + +## Validation evidence + +Environment: Debian Linux kernel `7.2.12+deb13-amd64`, x86-64; GCC `14.2.0`; +Python `3.13.5`; SDL headers `3.5.0`; SDL dummy video + software renderer and +dummy audio for graphics tests. Logs are under ignored +`build/validation/R0.4/logs/`. + +All commands were run from the repository root. The correction reruns below +were executed for this review against the tree based on commit `533c8e9`; +earlier baseline rows are retained from the preceding report and were **not** +rerun for this correction. + +### Rerun after the archive-integrity correction + +| Command | Exit | Result | +| --- | ---: | --- | +| `python3 -m unittest discover -s tests -p test_render.py -v` | 0 | 9 tests in 6.415s; 6 passed, 3 owned-data skips; both new end-to-end archive-integrity negatives passed | +| `python3 -m unittest discover -s tests -v` | 0 | 156 tests in 109.715s; 135 passed, 21 skipped, 0 failures/errors | +| `python3 -m py_compile tests/visual_baseline.py tests/test_render.py` | 0 | no output | +| `git diff --check` | 0 | no output | + +The full-regression stdout was retained outside the repository at +`/tmp/opencode/r04-full.log`; no log or generated artefact was added to source +control. + +### Earlier baseline validation, not rerun for this correction + +| Command | Exit | Result | +| --- | ---: | --- | +| `python3 -m unittest discover -s tests -p test_render.py -v` | 0 | 7 tests in 5.273s; 4 passed, 3 owned-data skips; baseline and negative comparator tests passed | +| `python3 -m unittest discover -s tests -p test_display.py -v` | 0 | 5 tests in 8.396s; 3 passed, 2 owned-data skips | +| `python3 -m unittest discover -s tests -p test_presentation.py -v` | 0 | 3 tests in 4.091s; 2 passed, 1 owned-data skip | +| `python3 -m unittest discover -s tests -p test_classic.py -v` | 0 | 12 tests in 10.671s; 8 passed, 4 owned-data skips | +| review-capture command above | 0 | 7 tests in 5.310s; 32 indexed files, 32 valid 8-bit BMPs and one manifest generated | +| `python3 -m unittest discover -s tests -v` | 0 | 154 tests in 105.727s; 133 passed, 21 skipped, 0 failures/errors | + +The supplied pre-R0.4 full suite was 153 total / 132 passed / 21 skipped. The +R0.4 baseline added one comparator unittest (154 / 133 / 21); this correction +adds two end-to-end archive-integrity unittests (156 / 135 / 21). No owned-data +or installation skip was converted into a pass. + +## Acceptance status + +| Criterion | Status | Evidence | +| --- | --- | --- | +| **A11 reproducible captures and metadata** | **PASS** | A clean synthetic path generates all 32 captures without proprietary data. Multiple update/ordinary/focused runs produced the locked hashes; the ordinary command validates the archive ID set, every archived capture's dimensions and SHA-256, fixture, palette, candidate pixels, metadata and restored-state equality. | +| **A12 visual inspection of required modes** | **PASS (reviewed synthetic captures)** | On 2026-11-22, the project owner inspected the generated BMP captures and reported that they looked fine. This is a user-reported visual sign-off, not an independently witnessed image-by-image assessment. Physical fullscreen, accelerated output, high-DPI and untested platforms remain NOT RUN. | +| **A13 regression detection and platform variance** | **PASS** | Automated tests prove identical pixels pass, a single changed pixel fails with count/bounds, dimension and metadata mismatch fail, and `validate_manifest()` rejects a missing archive entry and corrupted archived pixels even when candidate hashes agree. Canonical indexed and stable software paths are exact; unsupported accelerated/physical/high-DPI configurations are explicitly outside the pixel-identity claim, not hidden by a tolerance. | + +For the synthetic baseline scope exercised and visually reviewed, R0.4 is signed off. This does not assert that untested platform or physical-display gates passed. + +## Human visual sign-off + +- **Date:** 2026-11-22 (Australia/Adelaide). +- **Reviewer:** project owner (user-reported). +- **Evidence:** after generating the R0.4 BMP captures using the documented workflow, the owner stated "look fine" and authorised recording approval. +- **Scope:** generated synthetic Classic/Enhanced BMP review captures; no separate record of individual image results or detailed hardware/backend inspection was supplied. +- **Decision:** A12 PASS for the generated synthetic baseline captures only. +- **Not run:** independent image-by-image audit, accelerated-renderer capture comparison, actual physical fullscreen, high-DPI, Windows/macOS and other untested configurations. + +## Manual inspection checklist + +Run the retained-capture command, record reviewer/date/OS/GPU/SDL driver, and +inspect every named state. At minimum confirm: + +- Classic 640x480 is corrected 4:3; 1280x720 has equal black side bars; + 1001x601 is centered and not stretched or cropped. +- Enhanced 4:3 agrees vertically with Classic while 16:9, 16:10, 21:9 and 32:9 + reveal additional horizontal geometry without stretching. +- corridor walls/door, near and far statics and actor have plausible depth and + occlusion; HUD and weapon remain centered and unclipped; +- door closed/half/open and pushwall initial/moving/boundary states progress in + the expected direction without gaps or overdraw; +- edge sprites/walls clip at the viewport and never overwrite the bevel/HUD; +- Auto 1001x601 uses the expected wide canvas; initial and restored images are + visually identical; +- on any available accelerated, high-DPI or physical-fullscreen target, record + PASS/FAIL/NOT RUN separately rather than comparing it to software pixels with + an invented tolerance. + +## Limitations and remaining risks + +- Human visual approval is recorded for the generated synthetic BMP captures. The owner reported that they looked fine; no granular per-image checklist or external reviewer evidence was provided. +- No owned Wolfenstein data was available; 21 existing compatibility or + installation tests skipped exactly as before. Synthetic baseline coverage is + independent of those assets. +- Only Linux x86-64 with SDL dummy/software was executed. Windows, macOS, + accelerated renderers, real fullscreen, high-DPI and multiple GPUs are NOT + RUN for this revision. +- Canonical Classic output scaling is a small test-side indexed oracle. Actual + SDL palette upload, logical rectangle and full-output geometry are separately + covered by the existing video/display tests, not by assuming every backend's + final pixels are identical. +- The semantic source revision avoids an impossible manifest hash depending on + the commit that contains itself. Git provenance is carried by the containing + commit and this report. +- Archive integrity proves consistency between the committed manifest, archive + and generated candidate; it is not a signature or external authenticity proof + for the committed manifest itself. + +## Files changed + +This integrity correction changed only `tests/visual_baseline.py`, +`tests/test_render.py`, `docs/automation/PLAYBOOK.md` and this report. The +committed manifest, archive, production C and capture scene were unchanged. The +cumulative R0.4 file set is: + +- `tests/render_tests.c` +- `tests/test_render.py` +- `tests/visual_baseline.py` +- `tests/fixtures/visual_baselines.json` +- `tests/fixtures/visual_baselines.zip` +- `docs/automation/PLAYBOOK.md` +- `docs/milestones/R0/R0.4.md` + +## Rollback + +Revert the commit containing this report. That removes only test capture code, +the comparator, synthetic baseline fixtures and documentation. No production +binary, user configuration, save, asset or content migration requires repair. +Generated evidence under `build/validation/R0.4/` is ignored and may be removed +independently. + +## R0.5 handoff + +R0.4 is signed off for the reviewed synthetic baseline scope. Begin R0.5 as the +separately scoped sanitizer/profiling baseline; do not reinterpret the R0.4 +skipped owned-data/platform cases as passes. Reproduce R0.4 with: + +```sh +timeout 240s python3 -m unittest discover -s tests -p test_render.py -v +``` diff --git a/docs/milestones/R0/R0.5.md b/docs/milestones/R0/R0.5.md new file mode 100644 index 00000000..925e15dd --- /dev/null +++ b/docs/milestones/R0/R0.5.md @@ -0,0 +1,296 @@ +# R0.5 Sanitizer and performance baseline evidence + +**Revision:** R0.5 + +**Branch:** `docs/revival-roadmap-and-validation` + +**Base commit:** `4f3bb4ddc741914d825c0822fd26d9c6e73fadbf` + +**Reviewed/corrected head:** `5b4e8fa` (review corrections applied on top) + +**Status:** PASS for A14 and A15 for the tested synthetic scope; A16 PASS for the +recorded synthetic baseline. Milestone evidence is limited to the environment +and configurations actually executed below. + +## Review corrections (2026-11-22) + +- **SDL perf:** Renamed `sdl_total` to `frame_total` and documented that it + measures `GameDrawPaused() + VW_UpdateScreen()` (frame total), while + `sdl_convert`/`sdl_upload`/`sdl_present` are WL_PROFILE SDL presentation + phases. Fixed render dimensions are now explicitly set with + `render_auto=false` and verified via `VL_DisplayGet()` after `VL_DisplaySet()`; + logs include `META,sdl_render_selected,...,actual=WxH,auto=0,high_res=1`. +- **Reproduction workflow:** Added executable `tools/r0_5_synthetic_perf.py`, + which reuses `tests/game_fixtures.py`, compiles both benchmark binaries, runs + CPU and SDL(dummy/software) measurements, and writes logs/CSV/summary under + ignored `build/validation/R0.5/`. +- **Sanitizer coverage:** Documented which suites execute instrumented C harness + binaries and which also invoke the prebuilt unsanitized `WOLF3D_BINARY`. +- **Validation rerun:** Re-ran perf workflow and full regression (156 tests, OK, + skipped=21, exit 0). + + +## Purpose and scope + +R0.5 establishes a sanitizer and performance baseline for the current synthetic +test scope. It covers AddressSanitizer/UndefinedBehaviorSanitizer execution of +representative synthetic C harnesses, lifecycle/restart, allocation/cleanup, +resource error paths, Classic rendering, Enhanced rendering, and reproducible +synthetic performance measurements. It does not introduce new gameplay behavior, +rendering changes, dependencies, or commercial asset requirements. + +## Environment + +| Item | Value | +| --- | --- | +| OS / kernel | Debian GNU/Linux 13 (trixie), Linux 7.2.12+deb13-amd64 x86_64 | +| CPU | 13th Gen Intel(R) Core(TM) i5-1340P, 16 CPUs (12 cores / 1 socket / 2 threads per core) | +| Compiler | gcc (Debian 14.2.0-19) 14.2.0 | +| ASan runtime package | libasan8:amd64 14.2.0-19 | +| SDL headers/build | SDL 3.5.0 headers; static lib `../cart/vendor/SDL/build/libSDL3.a` | +| Python | Python 3.13.5 | +| Data | Synthetic fixtures generated in-repo by test harnesses; no owned WL6 data required for mandatory checks | + +Raw logs and generated benchmark data are under ignored `build/validation/R0.5/`. + +## A14 — ASan/UBSan execution + +### Method + +Representative synthetic Python unittest suites were executed with `SANITIZE=1`. +The test harnesses add `-fsanitize=address,undefined -fno-omit-frame-pointer` +to GCC compile flags when `SANITIZE=1` is set (verified in the existing test +wrappers, e.g. `tests/test_engine.py`, `tests/test_render.py`, +`tests/test_display.py`, `tests/test_presentation.py`, `tests/test_classic.py`). + +Commands were run from the repository root. Each command was bounded by an +external `timeout` and its stdout/stderr was captured to a log file; the exit +code was appended to the log. + +### Instrumentation scope + +| Suite | Instrumented C binaries | Unsanitized app executable possible | +| --- | --- | --- | +| `test_engine.py` | Yes — compiled engine/ui/game/combat/campaign/boss/finale harnesses with SANITIZE flags | **Yes** — some tests invoke prebuilt `WOLF3D_BINARY` (`--check-ui`, `--check-level`, `--menu --frames`, malformed-data app runs) | +| `test_config.py` | Yes — compiled config-tests with SANITIZE flags | **Yes** — `app_run` invokes prebuilt `WOLF3D_BINARY` | +| `test_signon.py` | Yes — compiled signon-tests with SANITIZE flags | Possible by test design (`cls.app` assigned); no WOLF3D_BINARY app-run invocation observed in sanitizer-focused signon harness path, but coverage claim is limited to instrumented harness execution | +| `test_render.py`, `test_classic.py`, `test_display.py`, `test_presentation.py`, `test_save.py`, `test_controls.py`, `test_loading.py`, `test_audio.py`, `test_dos_menus.py`, `test_dos_ui_reference.py`, `test_demo_sync.py` | Yes — compiled test harness binaries with SANITIZE flags | No WOLF3D_BINARY invocation identified in these wrappers | + +Sanitizer findings can only be reported for instrumented code paths. App +subprocesses using a prebuilt non-ASan/UBSan binary are outside ASan +instrumentation and are not claimed as sanitizer-covered. + +### Sanitizer command matrix + +| Command | Timeout | Exit | Log | Result | +| --- | ---: | ---: | --- | --- | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_engine.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_engine.log` | 41 tests, OK (skipped=1) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_render.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_render.log` | 9 tests, OK (skipped=3) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_classic.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_classic.log` | 12 tests, OK (skipped=4) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_display.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_display.log` | 5 tests, OK (skipped=2) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_presentation.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_presentation.log` | 3 tests, OK (skipped=1) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_save.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_save.log` | 6 tests, OK (skipped=0) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_config.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_config.log` | 3 tests, OK (skipped=0) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_controls.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_controls.log` | 2 tests, OK (skipped=0) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_loading.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_loading.log` | 3 tests, OK (skipped=0) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_audio.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_audio.log` | 5 tests, OK (skipped=1) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_signon.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_signon.log` | 5 tests, OK (skipped=1) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_dos_menus.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_dos_menus.log` | 6 tests, OK (skipped=0) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_dos_ui_reference.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_dos_ui_reference.log` | 2 tests, OK (skipped=0) | +| `SANITIZE=1 python3 -m unittest discover -s tests -p test_demo_sync.py -v` | 1200s | 0 | `build/validation/R0.5/logs/sanitize-test_demo_sync.log` | 2 tests, OK (skipped=0) | + +Coverage intent of the selected suites: + +- **Lifecycle/restart, allocation and cleanup, resource error paths:** `test_engine.py`, `test_save.py`, `test_config.py`, `test_loading.py`, `test_demo_sync.py`. +- **Classic rendering:** `test_classic.py`, `test_render.py` synthetic Classic captures. +- **Enhanced rendering:** `test_render.py`, `test_display.py`, `test_presentation.py`. +- **SDL/platform lifecycle and resource paths:** `test_display.py`, `test_signon.py`, `test_audio.py`, `test_controls.py`, `test_dos_menus.py`, `test_dos_ui_reference.py`. + +All sanitizer logs were scanned for `AddressSanitizer`, `UndefinedBehaviorSanitizer`, +`LeakSanitizer`, `runtime error:` and `SUMMARY:`; no matches were found. + +### A14 status + +**PASS** for the tested synthetic scope. Exact compiler/runtime versions, +commands, timeouts, exit codes and log paths are recorded above. Coverage is +limited to instrumented binaries; unsanitized app subprocesses are documented. + +## A15 — Application-owned sanitizer findings + +No application-owned ASan/UBSan/LSan/runtime-error findings were observed in the +executed sanitizer matrix. No code changes were required to resolve sanitizer +findings for this revision. + +Skips in sanitizer runs are the same class as normal runs (owned Wolfenstein +data or environment-dependent cases) and are not reported as sanitizer passes. + +### A15 status + +**PASS** — no application-owned ASan/UBSan/LSan/runtime-error findings observed in the executed instrumented synthetic matrix. Unsanitized prebuilt `WOLF3D_BINARY` subprocesses, where present, are outside this claim. This is not a claim that all possible execution paths are sanitizer-clean; it is bounded by the suites and environment listed above. + +## A16 — Performance baseline + +### Method + +A synthetic performance benchmark harness, `tests/synthetic_perf_benchmark.c`, +was added. It uses only synthetic game fixtures (`game_files()` from +`tests/game_fixtures.py`), requires no owned WL6 data, and reports CSV output. + +Two binaries are compiled: + +- CPU-only: GCC 14.2.0, `-std=c11 -O2 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror -g`, linked with SDL3 static lib for timing. +- SDL-profile: same flags plus `-DWOLF3D_BENCHMARK` to enable existing WL_PROFILE instrumentation and separate convert/upload/present phases. + +### Reproducible workflow + +Executable workflow (preferred): + +```sh +python3 tools/r0_5_synthetic_perf.py --timeout 600 +``` + +This script checks prerequisites, generates synthetic fixtures via +`tests/game_fixtures.py`, compiles both binaries, runs CPU and SDL(dummy/software) +benchmarks, and writes logs/CSV/summary under ignored `build/validation/R0.5/`. +Raw outputs: `build/validation/R0.5/logs/perf-cpu.stdout.log`, +`build/validation/R0.5/logs/perf-sdl.stdout.log`, +`build/validation/R0.5/logs/perf-cpu.csv`, +`build/validation/R0.5/logs/perf-sdl.csv`, +`build/validation/R0.5/perf-summary.txt`. + +### CPU renderer baseline (synthetic, CPU-only) + +Exit: 0. Raw log: `build/validation/R0.5/logs/perf-cpu.stdout.log`. + +Scene setup is deterministic and programmatic: "empty" has walls/bounds and no +actors/statics/doors; "populated" adds two statics, one guard actor, and one +closed door. Both use fixed player position/angle, view size 19, pistol weapon, +and `GameDrawPaused()` before warmup. Warmup: 20 frames; measured: 200 frames. +CPU renderer is measured via `WL_RenderFrameAspect()` only (no SDL upload/present). + +| Scene | Mode | Resolution | Min ms | Mean ms | P50 ms | P95 ms | P99 ms | Max ms | RSS KiB | +| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| empty | cpu_render | 320x200 | 0.162929 | 0.245367 | 0.211639 | 0.416523 | 0.478328 | 0.610094 | 18960 | +| empty | cpu_render | 640x480 | 0.661602 | 0.762630 | 0.672612 | 1.180941 | 1.239382 | 1.344536 | 18960 | +| empty | cpu_render | 1280x720 | 1.782131 | 1.810606 | 1.805533 | 1.837686 | 1.910305 | 1.965885 | 18960 | +| empty | cpu_render | 1920x1080 | 3.936534 | 4.081808 | 3.989934 | 4.080986 | 6.439424 | 7.686537 | 18960 | +| populated | cpu_render | 320x200 | 0.164491 | 0.167310 | 0.166461 | 0.171459 | 0.176151 | 0.230461 | 18960 | +| populated | cpu_render | 640x480 | 0.669661 | 0.677557 | 0.675438 | 0.682905 | 0.725502 | 0.797903 | 18960 | +| populated | cpu_render | 1280x720 | 1.783821 | 1.812430 | 1.808336 | 1.838254 | 1.879653 | 2.023869 | 18960 | +| populated | cpu_render | 1920x1080 | 3.928064 | 4.524372 | 3.977765 | 8.116097 | 12.062744 | 12.806698 | 18960 | + +### SDL frame total and presentation overhead (synthetic, dummy/software) + +Command (executed by reproduction workflow): + +```sh +SDL_VIDEODRIVER=dummy SDL_RENDER_DRIVER=software SDL_AUDIODRIVER=dummy \ + ./build/validation/R0.5/synthetic_perf_bench_sdl \ + build/validation/R0.5/perf-data build/validation/R0.5/perf-user-sdl --sdl +``` + +Exit: 0. Raw log: `build/validation/R0.5/logs/perf-sdl.stdout.log`. + +Fixed render dimensions are explicitly selected per case: +`high_resolution=true`, `render_auto=false`, `render_width=w`, +`render_height=h`. After `VL_DisplaySet()`, the benchmark reads back +`VL_DisplayGet()` and checks `high_resolution && !render_auto && +render_width==w && render_height==h`. Logs record +`META,sdl_render_selected,...,actual=WxH,auto=0,high_res=1`. + +Measurement distinction: + +- `frame_total`: wall-clock time around `GameDrawPaused()` + `VW_UpdateScreen()` (game draw plus SDL update path). +- `sdl_convert`, `sdl_upload`, `sdl_present`: WL_PROFILE SDL presentation-phase deltas inside the SDL path. +- CPU renderer-only measurements are reported separately in the CPU table above. + +Warmup: 20 frames; measured: 120 frames. RSS is `ru_maxrss` (Linux KiB). + +| Scene | Mode | Resolution | Min ms | Mean ms | P50 ms | P95 ms | P99 ms | Max ms | RSS KiB | +| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| populated | frame_total | 640x480 | 6.024102 | 6.285701 | 6.234236 | 6.634556 | 6.765585 | 8.371068 | 18960 | +| populated | sdl_convert | 640x480 | 0.196764 | 0.202864 | 0.198124 | 0.219036 | 0.246274 | 0.345017 | 18960 | +| populated | sdl_upload | 640x480 | 0.091803 | 0.113874 | 0.111618 | 0.129100 | 0.157756 | 0.264485 | 18960 | +| populated | sdl_present | 640x480 | 4.957810 | 5.220023 | 5.178958 | 5.561654 | 5.758880 | 6.453615 | 18960 | +| populated | frame_total | 1280x720 | 3.565710 | 4.094992 | 3.744806 | 5.698414 | 6.195124 | 8.630784 | 20412 | +| populated | sdl_convert | 1280x720 | 0.575715 | 0.643262 | 0.580758 | 0.960399 | 1.005006 | 1.648025 | 20412 | +| populated | sdl_upload | 1280x720 | 0.308548 | 0.451661 | 0.423356 | 0.648711 | 0.771581 | 0.798605 | 20412 | +| populated | sdl_present | 1280x720 | 0.604245 | 0.707696 | 0.655558 | 1.043541 | 1.123685 | 1.164229 | 20412 | +| populated | frame_total | 1920x1080 | 11.735764 | 12.918577 | 11.972271 | 17.723888 | 24.656617 | 33.845148 | 31328 | +| populated | sdl_convert | 1920x1080 | 1.286133 | 1.396540 | 1.293579 | 2.063020 | 2.792281 | 3.124513 | 31328 | +| populated | sdl_upload | 1920x1080 | 0.956411 | 1.131518 | 1.025637 | 1.629334 | 2.483329 | 3.279591 | 31328 | +| populated | sdl_present | 1920x1080 | 5.069440 | 5.694087 | 5.253332 | 8.703629 | 11.103367 | 14.021463 | 31328 | + +### A16 status + +**PASS** for recorded synthetic baseline evidence. The report includes raw logs, +exact commands, compiler flags, CPU/OS/SDL details, resolutions, frame-time +distributions, and observable RSS/heap (`MM_TotalBytes` end-of-run) data. +Frame total and SDL presentation phases are distinguished, and fixed render +dimensions are explicitly selected and verified. No target FPS was invented or +asserted as a pass/fail gate. + +## Full regression + +Command: + +```sh +python3 -m unittest discover -s tests -v +``` + +Initial exit: 0. Log: `build/validation/R0.5/logs/full-regression.log`. +Result: Ran 156 tests in 209.891s, OK (skipped=21). + +Post-correction rerun exit: 0. Log: `build/validation/R0.5/logs/full-regression-rerun.log`. +Result: Ran 156 tests in 221.675s, OK (skipped=21). No failures/errors. + +## Findings and limitations + +- No application-owned ASan/UBSan findings were observed in the executed synthetic + sanitizer matrix. +- Sanitizer coverage is bounded to the selected suites and synthetic fixtures; it + is not a proof of absence of bugs in all paths. +- 21 full-regression tests remain skipped due to owned Wolfenstein data or + environment-dependent requirements; they were not converted to passes. +- Performance numbers are from one Linux x86-64 machine with SDL dummy/software + for the SDL presentation phase. They are baselines, not portable performance + claims. Variance spikes are visible in raw distributions (e.g. populated + 1920x1080 CPU p99/max, 1280x720 SDL present) and are reported, not smoothed. +- Allocation measurement is limited to observable `ru_maxrss` and end-of-run + `MM_TotalBytes()`; it is not a full allocator trace. +- No hardware-accelerated GPU presentation, physical display, Windows/macOS, or + owned-data WL6 performance run was executed for this revision. +- `tests/synthetic_perf_benchmark.c` is a new synthetic benchmark harness; it is + not yet wrapped by a canonical `tools/` command (R0.6 scope). + +## Acceptance matrix + +| Criterion | Status | Evidence | +| --- | --- | --- | +| **A14** ASan/UBSan results with exact compiler, runtime, commands and exit codes | **PASS** | 14 sanitizer suites executed with `SANITIZE=1`, GCC 14.2.0/libasan8 14.2.0-19, SDL 3.5.0, 1200s timeouts, all exit 0; logs in `build/validation/R0.5/logs/sanitize-*.log`. | +| **A15** All application-owned sanitizer findings resolved or blocked with explicit owner | **PASS** | No application-owned ASan/UBSan/LSan/runtime-error findings observed in executed matrix; no unresolved app-owned blocker identified. | +| **A16** Baseline benchmark raw logs stored, no invented target FPS result | **PASS** | Synthetic CPU and SDL-profile benchmarks recorded with raw logs, commands, compiler flags, CPU/OS/SDL metadata, distributions, RSS/MM_TotalBytes; no target FPS gate asserted. | + +## Files changed + +- `tests/synthetic_perf_benchmark.c` (synthetic perf benchmark harness; corrected frame_total/SDL phase distinction and render_auto verification) +- `tools/r0_5_synthetic_perf.py` (executable reproduction workflow) +- `docs/milestones/R0/R0.5.md` (this report) +- `docs/automation/PLAYBOOK.md` (R0.5 procedure/evidence notes) + +## Reproduce + +```sh +# Sanitizer (representative, bounded; see instrumentation scope table above) +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_engine.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_render.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_classic.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_display.py -v +SANITIZE=1 timeout 1200 python3 -m unittest discover -s tests -p test_presentation.py -v + +# Synthetic perf baseline (CPU + SDL dummy/software, logs/CSV under build/validation/R0.5/) +python3 tools/r0_5_synthetic_perf.py --timeout 600 + +# Full regression +timeout 1200 python3 -m unittest discover -s tests -v +``` diff --git a/docs/milestones/R0/R0.6.md b/docs/milestones/R0/R0.6.md new file mode 100644 index 00000000..12e26edd --- /dev/null +++ b/docs/milestones/R0/R0.6.md @@ -0,0 +1,201 @@ +# R0.6 Validation command surface evidence + +**Revision:** R0.6 + +**Branch:** `docs/revival-roadmap-and-validation` + +**Status:** PASS for A17–A19 on the tested Linux synthetic scope. The actual +GitHub Actions run for reviewed commit `2ff874b` is **FAIL**; its SDL static-build +configuration is corrected here but has not yet been rerun remotely. + +## Purpose and scope + +R0.6 implements a lightweight validation orchestrator over existing Python +unittest suites and scripts. It provides milestone selection, bounded execution, +clear progress/status reporting, per-job logs, and machine-readable JSON +summaries. It does not change gameplay, renderer, save formats, or add +dependencies. + +## Architecture + +- `tools/validation/run.py` — Python stdlib orchestrator. Defines explicit job + registry, selects jobs by milestone/category, runs each job in a new process + group, captures stdout/stderr to a log file, enforces per-job timeout with + process-group termination, writes `summary.json`. +- `tools/test.sh` — thin bash wrapper delegating to `run.py`. +- `tests/test_validation_runner.py` — orchestration unit tests (synthetic helper + commands; no full engine compile). + +Design choices: +- Reuse existing unittest suites and `tools/r0_5_synthetic_perf.py`; no test + framework rewrite. +- No third-party Python dependencies. +- Bounded allowlist for environment metadata in JSON (platform, python, cwd, cc). +- `WOLF3D_UPDATE_BASELINES` is removed from job environments to prevent + accidental baseline regeneration. + +## Job-to-milestone mapping + +| Job ID | Milestone | Category | Mandatory | Timeout | Command / scope | +| --- | --- | --- | --- | ---: | --- | +| `r03-engine-synthetic` | R0.3,R0.6,all | cpu | yes | 900s | `python3 -m unittest discover -s tests -p test_engine.py -v` | +| `r04-render` | R0.4,R0.6,all | graphics | yes | 600s | `... -p test_render.py -v` (synthetic baseline mandatory; owned skips allowed) | +| `r04-display` | R0.4,R0.6,all | graphics | yes | 600s | `... -p test_display.py -v` | +| `r04-presentation` | R0.4,R0.6,all | graphics | yes | 600s | `... -p test_presentation.py -v` | +| `r04-classic` | R0.4,R0.6,all | graphics | yes | 600s | `... -p test_classic.py -v` | +| `r05-san-engine` | R0.5,all | sanitizer | yes | 1200s | `SANITIZE=1 ... test_engine.py` | +| `r05-san-render` | R0.5,all | sanitizer | yes | 1200s | `SANITIZE=1 ... test_render.py` | +| `r05-san-classic` | R0.5,all | sanitizer | yes | 1200s | `SANITIZE=1 ... test_classic.py` | +| `r05-san-display` | R0.5,all | sanitizer | yes | 1200s | `SANITIZE=1 ... test_display.py` | +| `r05-san-presentation` | R0.5,all | sanitizer | yes | 1200s | `SANITIZE=1 ... test_presentation.py` | +| `r05-san-save` | R0.5,all | sanitizer | yes | 1200s | `SANITIZE=1 ... test_save.py` | +| `r05-san-config` | R0.5,all | sanitizer | yes | 1200s | `SANITIZE=1 ... test_config.py` | +| `r05-san-controls` | R0.5,all | sanitizer | yes | 900s | `SANITIZE=1 ... test_controls.py` | +| `r05-san-loading` | R0.5,all | sanitizer | yes | 900s | `SANITIZE=1 ... test_loading.py` | +| `r05-san-audio` | R0.5,all | sanitizer | yes | 900s | `SANITIZE=1 ... test_audio.py` | +| `r05-san-signon` | R0.5,all | sanitizer | yes | 900s | `SANITIZE=1 ... test_signon.py` | +| `r05-san-dos-menus` | R0.5,all | sanitizer | yes | 900s | `SANITIZE=1 ... test_dos_menus.py` | +| `r05-san-dos-ui-reference` | R0.5,all | sanitizer | yes | 900s | `SANITIZE=1 ... test_dos_ui_reference.py` | +| `r05-san-demo-sync` | R0.5,all | sanitizer | yes | 1200s | `SANITIZE=1 ... test_demo_sync.py` | +| `r05-perf-synthetic` | R0.5,all | performance | yes | 1200s | `python3 tools/r0_5_synthetic_perf.py --timeout 600` | +| `r06-runner-tests` | R0.6,all | meta | yes | 300s | `python3 -m unittest discover -s tests -p test_validation_runner.py -v` | + +Mandatory means required for the selected milestone; failure/timeout/NOT RUN of a +mandatory job fails the overall run. Optional jobs (none currently registered) +may SKIP/NOT RUN without failing the milestone when explicitly marked optional. + +## Commands and options + +```sh +python3 tools/validation/run.py R0.3|R0.4|R0.5|R0.6|all +python3 tools/validation/run.py R0.6 --dry-run +python3 tools/validation/run.py R0.6 --list +python3 tools/validation/run.py R0.5 --category sanitizer +python3 tools/validation/run.py R0.6 --job r06-runner-tests + +tools/test.sh # default R0.6 +tools/test.sh --graphics # R0.4 graphics category +tools/test.sh --sanitizer # R0.5 sanitizer category +tools/test.sh --performance # R0.5 performance category +tools/test.sh --all # all milestones/jobs +``` + +## Progress, timeout, and failure behavior + +Each job prints `START [milestone] id: description` with timeout and command. +Jobs run in a new process group (`start_new_session=True`); on timeout the runner +sends SIGTERM to the process group, waits briefly, then SIGKILL, preventing +orphan child processes. Each job ends with `PASS|FAIL|TIMEOUT|SKIP|NOT RUN`, +exit code, and duration. Missing mandatory prerequisites are reported as +`NOT RUN` and fail the overall run. A compile is never reported as a test pass; +the runner reports the test command's exit status. A zero-exit direct parent is +also FAIL if a non-zombie descendant remains in its captured session/process +group. Linux `/proc` state and start-time checks exclude zombies and prevent +signalling a PID identity that was reused. + +## JSON summary schema + +`build/validation///summary.json` (schema_version 1): + +- `milestone`, `started_at`, `ended_at`, `duration_s`, `overall_status` +- `environment`: bounded allowlist (`platform`, `python`, `cwd`, `cc`) +- `jobs[]`: `id`, `milestone`, `description`, `command`, `category`, `mandatory`, + `timeout`, `status`, `exit_code`, `duration_s`, `started_at`, `ended_at`, + `log_file`, `message` + +Per-job logs are written as `.log` in the same run directory. + +## CI configuration + +`.github/workflows/validation.yml` runs on push to +`docs/revival-roadmap-and-validation` and on pull requests targeting `master` +(repository default branch); it also supports `workflow_dispatch`. It executes +`python3 tools/validation/run.py R0.6` (mandatory synthetic CPU+graphics+runner +tests) on `ubuntu-latest` with SDL3 built/cached, dummy video/software render/ +dummy audio. Validation logs are uploaded as artifacts on failure. + +Not run in CI by default: sanitizer and performance jobs (separately selectable), +owned-data WL6 tests, GPU/physical-display checks. + +PR #18 run `45017643120` at commit `2ff874b` completed with conclusion +**failure**. Job `137193318288` failed in `Build SDL3 (if cache miss)` before +validation ran: SDL 3.2.8 reported `SDL_SHARED and SDL_STATIC cannot both be +disabled`. This revision explicitly passes `-DSDL_STATIC=ON`. No passing remote +result is claimed until the branch is pushed and Actions reruns. + +## Validation outcomes (actual) + +Environment: Debian GNU/Linux 13, Linux 7.2.12+deb13-amd64, 13th Gen Intel Core +i5-1340P, GCC 14.2.0, Python 3.13.5, SDL 3.5.0 static build. + +| Command | Exit | Result / evidence | +| --- | ---: | --- | +| `python3 -m unittest discover -s tests -p test_validation_runner.py -v` | 0 | 19 tests, OK in 9.543s | +| `python3 -m unittest discover -s tests -v` | 0 | 175 tests, OK (skipped=21), 206.693s; log `build/validation/R0.6/full-regression-final-correction.log` | +| `python3 tools/validation/run.py R0.6` | 0 | 6 mandatory jobs PASS, overall PASS; `build/validation/R0.6/20261122T115322Z/summary.json` | +| `git diff --check` | 0 | clean | + +Previous R0.6 validation (commit `d7e786e`, before review corrections): R0.3/R0.4/R0.5/R0.6 runner PASS, 167 tests OK (21 skipped). See `build/validation/R0.6/full-regression.log`. + +## Acceptance matrix + +| Criterion | Status | Evidence | +| --- | --- | --- | +| **A17** Clean-checkout mandatory synthetic validation | **PASS** | R0.6 run executes engine+render+display+presentation+classic+runner tests without owned WL6 assets; owned-data cases skip, mandatory synthetic checks pass. | +| **A18** Correct milestone selection and nonzero on required failure | **PASS** | Explicit job mapping; `--list/--dry-run` show selection; runner unit tests prove required failure => overall FAIL, unknown milestone rejected. | +| **A19** Accurate hangs/unsupported/skip/NOT RUN handling | **PASS** | Normal parent+child completion passes; zero/nonzero parents with live descendants fail and clean up; timeout returns TIMEOUT; a TERM-ignoring child is killed; zombies are not treated as running; missing mandatory prereq => NOT RUN+overall FAIL. | + +## Review corrections (post-d7e786e) + +- **Process-group cleanup:** `kill_process_group()` no longer returns when the + direct child has exited; it escalates TERM→KILL over the captured pgid, + reaps the direct child, and performs best-effort post-wait cleanup for + descendants. Regression tests cover parent+child running, parent exited with + child still running/holding stdout, child ignoring SIGTERM, and process group + already gone. +- **Incremental log streaming:** jobs stream stdout/stderr directly to the log + file (`stdout=log, stderr=STDOUT`) instead of buffering via `communicate()`. + Memory usage is bounded; logs remain useful on timeout; JSON format unchanged. +- **CI triggers/build:** pull_request targets `master` (default branch); push + retained for `docs/revival-roadmap-and-validation`; `workflow_dispatch` added. + CI now builds the production app via `tools/ci_build_app.sh` (cart.toml-aligned + GCC+SDL3 static build, no CART dependency, no proprietary assets), sets + `WOLF3D_BINARY`, and fails immediately if the executable is missing. + +## Final correction (post-2ff874b) + +- **Whole-process-tree completion:** `run_job()` checks the captured session + after the direct parent exits. A running descendant makes the job FAIL even + when the parent returned zero; nonzero and timeout semantics remain FAIL and + TIMEOUT respectively. +- **Bounded identity-safe cleanup:** Linux `/proc//stat` inspection filters + zombie state and records process start ticks. TERM and KILL are sent only + after rechecking captured identities, with one-second bounded waits. The + already-gone case remains a safe no-op. +- **Regression coverage:** tests separately cover normal parent/child exit, + zero-exit orphan failure, nonzero-exit orphan failure, parent/child timeout, + TERM-ignoring child escalation, already-gone cleanup, zombie exclusion and + refusal to target a mismatched/reused leader identity. +- **CI SDL correction:** the workflow now enables `SDL_STATIC=ON`, addressing + the actual SDL 3.2.8 CMake failure in PR #18 run `45017643120`. + +## Known limitations + +- Sanitizer jobs are instrumented-harness coverage as documented in R0.5; app + subprocesses through prebuilt `WOLF3D_BINARY` are not ASan-instrumented. +- Owned WL6 data tests remain environment-dependent skips; not claimed as passes. +- PR #18 Actions at reviewed commit `2ff874b` is confirmed FAIL before tests due + to the SDL CMake option above. This correction has no remote conclusion until + committed/pushed and rerun. +- Performance jobs are evidence-only; no FPS target gate. +- `all` includes sanitizer/perf and can be expensive; CI default uses R0.6. +- Identity-safe zombie filtering is implemented and tested on Linux `/proc`. + Non-Linux POSIX uses the conservative process-group probe and was NOT RUN; no + cross-platform zombie-filtering claim is made. + +## R0.7 handoff + +R0.6 provides the command surface and evidence capture needed for R0.7 baseline +sign-off. R0.7 should review R0.1–R0.6 evidence, record A01–A19 matrix, and +obtain explicit architecture/test review before R1/R2. Do not begin R0.7 in this +revision. diff --git a/docs/milestones/R0/R0.7.md b/docs/milestones/R0/R0.7.md new file mode 100644 index 00000000..b0af48b1 --- /dev/null +++ b/docs/milestones/R0/R0.7.md @@ -0,0 +1,227 @@ +# R0.7 Foundation review and baseline sign-off recommendation + +**Revision:** R0.7 + +**Branch:** `docs/revival-roadmap-and-validation` + +**Audited source commit:** `b29000068f81ff152c8c6a47db2668a5a0308506` + +**Review date:** 23 November 2026 (Australia/Adelaide) + +**Status:** **PASS**. The tested Linux synthetic baseline and architecture review support R0 sign-off. An independent ChatGPT reviewer has explicitly approved the architecture/test review (A22). R0 is now CLOSED for the documented Linux synthetic scope. No R1 or R2 implementation is authorised by this report. + +## Purpose and scope + +R0.7 reviews the complete R0.1-R0.6 foundation, reruns the canonical validation +surface, inspects the implementation against the planned R1/R2 work, and records +the remaining approval and platform/licensing boundaries. It does not change +gameplay, renderer behavior, formats, assets, dependencies, or production C. + +In scope: + +- independent review of A01-A19 against source, tests and current executions; +- current Linux build, synthetic CPU/graphics, ASan/UBSan, performance and + validation-runner evidence; +- manual review of the retained synthetic Classic/Enhanced captures; +- architecture readiness and future content-system requirements; and +- an R0 sign-off recommendation with unresolved issues stated explicitly. + +Out of scope: + +- R1 IP separation or R2 content-loader implementation; +- PK3/ZIP parsing, a virtual filesystem, new map/resource formats or Workshop; +- gameplay changes, renderer refactoring or proprietary asset distribution; +- physical Windows/macOS/Android, accelerated GPU, high-DPI or fullscreen + validation; and +- legal clearance or approval on behalf of the final reviewer. + +## Review method and current evidence + +The review read `AGENTS.md`, `docs/plan.md`, the R0 plan and all R0.1-R0.6 +reports (including the R0.4.1 inventory), the test strategy, automation +playbook, original-content/IP proposal and Workshop proposal. It then inspected +the current loader, lifecycle, renderer, presentation, platform and test code. + +Current environment: + +| Item | Value | +| --- | --- | +| Host | Debian GNU/Linux 13, Linux `7.3.4+deb13-amd64`, x86-64 | +| Compiler | GCC `14.2.0` (`gcc (Debian 14.2.0-19)`) | +| Python | `3.13.5` | +| SDL | local static SDL headers/library `3.5.0` | +| CART | `0.2.0`; C11 `cart-sdl` profile | +| Graphics test backend | SDL dummy video, software renderer, dummy audio | +| Data | project-authored synthetic fixtures; no owned WL6 path supplied | + +Executed commands and results are consolidated in +[`VALIDATION.md`](VALIDATION.md). The principal current run was: + +```sh +python3 tools/validation/run.py all +``` + +It exited `0`: all 21 mandatory jobs passed, covering 237 unittest executions +(205 executed passes and 32 explicit owned-data/environment skips) plus the +performance workflow. The machine-readable record is +`build/validation/ALL/20261123T054239Z/summary.json`. The separate full +regression exited `0` with 175 tests, 154 passes and 21 skips. Sanitizer logs +contained no `AddressSanitizer`, `UndefinedBehaviorSanitizer`, `LeakSanitizer`, +`runtime error:` or sanitizer `SUMMARY:` signature. + +GitHub Actions run +[`45021864807`](https://github.com/raygibbon/wolf3d-revive/actions/runs/45021864807) +passed at the audited commit. Its `R0.6 mandatory synthetic +(CPU+graphics+runner)` job built the application from a clean checkout with SDL +3.2.8 and completed the R0.6 synthetic gate successfully. + +## Architecture readiness assessment + +### Findings + +| Area | Assessment | Evidence and consequence | +| --- | --- | --- | +| Engine/platform separation | **Ready baseline** | SDL includes are confined to `main.c` and `src/platform/`; engine harnesses compile with only the file adapters. Logical controls, audio and simulation are testable without devices. | +| Engine/game/content separation | **Prerequisite required** | `WL_DEF.h`, global runtime arrays, hard-coded resource numbers and WL6 names still combine engine mechanics with one game's definitions. R1 must classify identity/content; R2 must add content/world owners rather than extending these globals. | +| Asset ownership/lifetimes | **Usable but legacy-bound** | `ID_CA` owns graphics chunks, `ID_PM` owns cached pages, `ID_MAP` owns the cached map, and SDL owns presentation objects. Shutdown is explicit and partial-init cleanup is tested. Borrowed raw pointers are invalid after cache shutdown, so future APIs must expose qualified views/handles rather than these pointers. | +| Map loading | **Safe legacy adapter, not authoring model** | `CA_ReadMap` stages and bounds every fixed 64x64 plane before `CA_InstallMap`; `SetupGameLevel` validates selection, spawn, enclosure, doors, textures and sprites before play. It supports only 60 WL6 slots and must remain an import/compatibility adapter. | +| Renderer/content independence | **PARTIAL** | Enhanced rendering can consume immutable presentation snapshots and caller-owned targets. Both renderers still obtain fixed 64x64 VSWAP pages, numeric shapes and global framebuffer/UI definitions; Classic also performs visibility/activation/bonus side effects. R2 needs one catalog/image-view boundary, not renderer-specific loaders. | +| Classic/Enhanced compatibility | **Ready baseline** | Exact 32-capture baselines cover Classic corrected 4:3 and Enhanced 4:3, 16:9, 16:10, 21:9, 32:9 and Auto plus doors, pushwalls, edge clipping, HUD and restoration. Physical backends remain untested. | +| Native C boundaries | **Suitable seam, incomplete future API** | Existing loader, simulation, snapshot, render-target and file-adapter functions are C11. No authored-world, package catalog, manifest or transaction API exists yet; R2/R4 must provide SDL-free ownership and errors before Workshop/UI use. | +| Headless testing | **Ready baseline** | Synthetic archive generation and C harnesses cover deterministic fixed-step behavior, malformed data, lifecycle, both render paths and failure injection without proprietary inputs. State isolation still depends on ordered global reset. | + +The current engine is therefore suitable for careful incremental R1/R2 work, +but it is not yet a general first-person creation engine. The recommended path +is to preserve the legacy adapter and both renderers while inserting small, +owned and testable content/world boundaries. A broad engine context, ECS, +renderer rewrite or Workshop-driven mutation of runtime globals is not justified. + +## Future content-system requirements + +These are requirements for future approved revisions, not implemented behavior +or ABI promises. + +### Package and development model + +1. Define one versioned package manifest before adding archive support. A + complete game package names its game identity, manifest/schema versions, + engine compatibility, campaigns and every required resource. Launch must + not silently fall back to legacy Wolfenstein data. +2. Resolve the same validated logical path namespace from either a loose + development directory or a PK3-compatible ZIP container. Directory and ZIP + inputs must produce the same catalog identity and diagnostics. +3. Treat PK3 as a packaging convention only. Reading ZIP files does **not** + imply ECWolf/GZDoom namespace, script, actor, map or mod compatibility. + Compatibility claims require separately specified adapters and fixtures. +4. Keep the first model simple: one selected complete base game package, with + optional explicitly ordered add-on packages only after deterministic + override and dependency rules are approved. Do not begin with GZDoom-style + implicit namespace behavior or a general scripting system. + +### Data and resource model + +- Use stable string or numeric content IDs resolved through an owned catalog, + never raw VSWAP page numbers outside the legacy adapter. +- Represent maps, textures, sprites/animation, audio, fonts/UI and metadata + with bounded descriptors carrying dimensions, formats, ownership, opacity, + pivots/scales and required/optional status. +- Define weapons, enemies, items and gameplay parameters as validated data while + native C owns deterministic behavior implementations. Unknown behavior IDs + fail clearly; data must not become unbounded executable scripting. +- Define campaigns as ordered map/objective/progression graphs with validated + starts, exits, unlocks and completion rules. Keep durable authored definitions + separate from transient actors, visibility, doors, pushwalls and save state. +- Build both Classic and Enhanced render inputs from the same catalog/resource + views. Preserve exact legacy 64x64 sampling through an adapter while adding + dimension-safe descriptors and explicit fixed-point rounding rules. + +### Selection, Workshop and export + +- The main menu enumerates validated complete game/mod packs and displays + identity, version, compatibility and validation errors before launch. +- Workshop uses the same authored-world and content IDs as gameplay. Its + create/edit/save/playtest/export operations call SDL-free native C APIs; UI + callbacks never own or directly mutate canonical world state. +- Playtest builds an isolated runtime session from a validated authored-world + snapshot. Returning to Workshop must not persist transient gameplay state. +- Export writes a deterministic loose directory or PK3-compatible ZIP from the + same validated catalog and manifest, using atomic output/recovery rules. Save, + playtest and export belong to later milestones after the R2 contract. + +### Validation and security + +- Reject absolute paths, `..` traversal, drive prefixes, ambiguous/case-colliding + names, duplicate entries, unsupported encryption/compression and symlink + escapes. Normalize names before catalog insertion. +- Apply explicit limits to archive bytes, entry count, individual and expanded + sizes, compression ratio, map/object/resource counts, image dimensions, + animation frames, audio duration and total memory. Check integer arithmetic + before allocation and decompression. +- Stage parsing and validation before publishing a catalog/world. On any error, + destroy partial state and return bounded machine-readable diagnostics with + package, path, resource ID and cause. +- Version manifests and formats independently. Unknown required fields or + incompatible major versions fail; migrations are explicit, deterministic and + fixture-tested. Checksums establish integrity, not authorship or licensing. +- Keep provenance and distribution rights in the package inventory. Security + validation does not confer permission to redistribute content. + +### Minimum native C ownership boundary + +R2 should specify opaque owners and caller-visible views for a package source, +validated manifest/catalog, resource image/audio data and authored world. Core +operations need bounded readers, enumeration/lookup, validation, error access, +legacy import, session construction and destruction. File/ZIP adapters and SDL +menu/Workshop presentation remain outside the core. Returned data is either +owned by the caller or borrowed for a documented owner lifetime; no hidden +global cache pointer crosses the boundary. + +## R1/R2 prerequisites and sequencing + +1. R1 completes the file-level licence/provenance and identity/reference audit, + defines legacy-content isolation and an original-only launch/package gate. +2. R2.1 freezes manifest, path, map, ID, version and limit contracts plus + malformed/migration fixtures before a ZIP decoder is selected. +3. R2.2 adds staged SDL-free parsing and diagnostics; R2.3 adds the shared + catalog/resource descriptors and legacy adapter. +4. R2.4 implements identical loose-directory and PK3-compatible resolution with + traversal, collision, size and decompression protections. +5. R2.5/R2.6 prove legacy parity, valid/malformed/old package handling, + deterministic catalog identity, bounded cleanup and both-renderer integration. +6. Main-menu selection, data-driven game breadth, Workshop, save/playtest and + export remain later approved slices; do not pull them into the first loader. + +## R0.7 acceptance + +| Criterion | Status | Evidence | +| --- | --- | --- | +| **A20** all critical criteria pass for tested targets | **PASS** | A01-A19 were checked against source and current execution. All mandatory Linux synthetic jobs passed, the complete regression passed with skips explicit, current sanitizer scans were clean, captures were reviewed, and performance evidence was recorded without an invented target. | +| **A21** out-of-scope platforms recorded separately | **PASS** | Linux dummy/software and prior MinGW/Wine evidence are separated from physical Windows, macOS, Android, accelerated GPU, high-DPI and fullscreen configurations, all of which remain NOT RUN. | +| **A22** architecture/test review explicitly approved before R1/R2 implementation | **PASS** | An independent ChatGPT reviewer has approved the architecture/test review and testing baseline for the documented Linux synthetic scope. | + +## Unresolved issues, impact and next action + +| Issue | Impact | Owner / next action | +| --- | --- | --- | +| Physical/platform coverage absent | Device/backend-specific display, input, audio, DPI and filesystem defects could remain. It does not invalidate the tested Linux baseline. | Future platform revisions: run and record physical Windows and other approved targets; do not backfill PASS. | +| Owned-data checks skipped locally | 21 compatibility/install tests were not rerun in this review. Latest no-skip owned-data evidence remains R0.1. | Reviewer with lawful data: optionally run the documented `WOLF3D_DATA=...` regression and retain private evidence outside Git. | +| Sanitized app subprocess gap | Some prebuilt `WOLF3D_BINARY` subprocess paths are not ASan/UBSan instrumented. | Future validation revision: add an explicitly sanitizer-built application only if approved; current harness claim remains bounded. | +| Legal clearance incomplete | Historical binaries/assets and external content cannot be represented as release-cleared. | R1 owner: complete provenance/licence audit and original-only staged-package gate. | +| Content/world API absent | PK3, loose packages, data-defined gameplay, menu selection and Workshop cannot safely be implemented on runtime globals. | R2/R4 owners after approval: implement the staged catalog/world boundaries in the ordered revisions above. | + +## Recommendation and handoff + +No tested-target technical blocker was found before R1/R2 planning. +R0 sign-off is complete for the documented Linux synthetic scope following +independent A22 approval. Do not start implementation. + +- **Modified files:** `docs/milestones/R0/R0.7.md` and + `docs/milestones/R0/VALIDATION.md` only. +- **Generated evidence:** ignored `build/validation/ALL/20261123T054239Z/`, + `build/validation/R0.5/` and `build/validation/R0.7/`. +- **Reusable procedure:** no new workflow was needed; the existing runner, + full regression, capture command, architecture inspection and CART build were + sufficient. The playbook therefore did not change. +- **Exact next command:** `git diff --check && git status --short` for document + review, followed by explicit reviewer disposition of A22. + diff --git a/docs/milestones/R0/VALIDATION.md b/docs/milestones/R0/VALIDATION.md new file mode 100644 index 00000000..41d8f89c --- /dev/null +++ b/docs/milestones/R0/VALIDATION.md @@ -0,0 +1,240 @@ +# R0 consolidated foundation validation + +**Milestone:** R0 baseline and test foundation + +**Audited source:** `b29000068f81ff152c8c6a47db2668a5a0308506` on +`docs/revival-roadmap-and-validation` + +**Validation date:** 23 November 2026 (Australia/Adelaide) + +**Overall:** **PASS — R0 milestone CLOSED for the documented Linux synthetic scope.** +A01-A22 pass within their stated evidence scopes. An independent ChatGPT +reviewer has explicitly approved the architecture/test review (A22). R0 +milestone is closed for the documented Linux synthetic scope. + +## Evidence sources and environment + +The current review inspected `docs/plan.md`, `docs/milestones/R0/PLAN.md`, every +R0.1-R0.6 report, current production/test/tooling source, the validation +strategy and automation playbook. Earlier evidence is not treated as current +execution unless identified below. + +| Item | Current review value | +| --- | --- | +| OS / kernel | Debian GNU/Linux 13; Linux `7.3.4+deb13-amd64`; x86-64 | +| Compiler | GCC `14.2.0` (`Debian 14.2.0-19`) | +| Python | `3.13.5` | +| SDL | local static SDK/headers `3.5.0` | +| CART / language | CART `0.2.0`; C11; `cart-sdl` profile | +| Graphics backend | `SDL_VIDEODRIVER=dummy`, software renderer, dummy audio | +| Current source | `b29000068f81ff152c8c6a47db2668a5a0308506` | +| CI | GitHub Actions run `45021864807`, success at the same commit; Ubuntu runner, SDL `release-3.2.8` | + +Generated evidence is intentionally ignored by Git: + +- `build/validation/ALL/20261123T054239Z/summary.json` and per-job logs; +- `build/validation/R0.5/perf-summary.txt` and `logs/perf-*.csv`; +- `build/validation/R0.7/full-regression.log`; +- `build/validation/R0.7/captures/manifest.json`, 32 `.w3i` files and 32 BMPs; +- `build/validation/R0.7/architecture-inspection.log` (1,511 lines); and +- `build/validation/R0.7/review/` contact sheets used for the current manual + synthetic-capture inspection. + +## Commands actually executed + +| Command | Exit | Result / evidence | +| --- | ---: | --- | +| `gh run view 45021864807 --repo raygibbon/wolf3d-revive --json ...` | 0 | Run conclusion `success`, head `b29000068...`; job `137206339344` and all required build/validation steps succeeded. | +| `python3 tools/validation/run.py all --list` | 0 | Listed 21 mandatory R0.3-R0.6 jobs with categories and timeouts. | +| `python3 tools/validation/run.py all` | 0 | 21 PASS, 0 FAIL/TIMEOUT/NOT RUN; 445.660 s. Summary: `build/validation/ALL/20261123T054239Z/summary.json`. | +| `python3 -m unittest discover -s tests -v` | 0 | Logged rerun: 175 tests in 155.082 s; 154 passed, 21 skipped, 0 failures/errors. Skips require owned WL6/DOS inputs or unavailable installations. Log: `build/validation/R0.7/full-regression.log`. | +| `WOLF3D_BASELINE_DIR="$PWD/build/validation/R0.7/captures" python3 -m unittest discover -s tests -p test_render.py -v` | 0 | 9 tests in 10.484 s: 6 passed, 3 owned-data skips; generated and validated 32 synthetic captures. | +| `./build/tools/cart build --profile cart-sdl --verbose` | 0 | C11 application linked successfully with GCC 14.2.0 and SDL 3.5.0; no compiler warning was emitted. | +| documented architecture inspection block from `PLAYBOOK.md` with destination changed to `R0.7` | 0 | 1,511-line sorted source/include/global inventory. SDL includes remained confined to `main.c` and `src/platform/`. | +| sanitizer signature scan over `r05-san-*.log` | 0 | No ASan, UBSan, LSan, `runtime error:` or sanitizer `SUMMARY:` match. | +| `git diff --check` | 0 | No whitespace error before report creation; rerun after edits is recorded in the final handoff. | + +The R0.3-R0.6 runner executed 237 unittest cases across normal and sanitizer +jobs: 205 executed passes and 32 explicit skips. These are test *executions*, +not 237 unique tests. The performance job is additional and is not counted as a +unittest. Per-job counts: + +| Job | Status | Tests | Skips | Seconds | +| --- | --- | ---: | ---: | ---: | +| `r03-engine-synthetic` | PASS | 41 | 1 | 59.3 | +| `r04-render` | PASS | 9 | 3 | 10.9 | +| `r04-display` | PASS | 5 | 2 | 14.4 | +| `r04-presentation` | PASS | 3 | 1 | 7.1 | +| `r04-classic` | PASS | 12 | 4 | 18.6 | +| `r05-san-engine` | PASS | 41 | 1 | 100.4 | +| `r05-san-render` | PASS | 9 | 3 | 19.7 | +| `r05-san-classic` | PASS | 12 | 4 | 23.7 | +| `r05-san-display` | PASS | 5 | 2 | 20.8 | +| `r05-san-presentation` | PASS | 3 | 1 | 13.7 | +| `r05-san-save` | PASS | 13 | 0 | 31.9 | +| `r05-san-config` | PASS | 29 | 1 | 11.1 | +| `r05-san-controls` | PASS | 3 | 1 | 8.2 | +| `r05-san-loading` | PASS | 2 | 1 | 29.9 | +| `r05-san-audio` | PASS | 6 | 1 | 13.8 | +| `r05-san-signon` | PASS | 16 | 2 | 9.8 | +| `r05-san-dos-menus` | PASS | 3 | 1 | 8.3 | +| `r05-san-dos-ui-reference` | PASS | 1 | 1 | 0.3 | +| `r05-san-demo-sync` | PASS | 5 | 2 | 7.2 | +| `r05-perf-synthetic` | PASS | n/a | n/a | 26.9 | +| `r06-runner-tests` | PASS | 19 | 0 | 9.7 | + +## Acceptance matrix A01-A22 + +Status applies to the criterion as written, not to unrelated future release +work. Platform and licensing exclusions are recorded separately below. + +| ID | Status | Current review evidence | +| --- | --- | --- | +| **A01** source/module and asset inventory complete with provenance status | **PASS** | R0.1 sections 2-8 enumerate active, historical, third-party, external and unverified material. Current `rg --files`, source and licence review found no basis to contradict it; legal clearance remains R1 work. | +| **A02** debug/release clean-checkout builds run and warnings recorded | **PASS** | R0.1 clean Linux optimized and strict debug builds and strict MinGW cross-build exited 0 with warnings recorded. Current CART profile build also exited 0 with no warning. The GitHub clean-checkout application build passed at the audited commit. | +| **A03** existing game smoke path documented | **PASS** | R0.1 records finite asset/UI/level and SDL smoke commands; the playbook retains them. Owned-data smoke was not rerun because no lawful data path was supplied. | +| **A04** no unverified licensing/test claims | **PASS** | Reports and this matrix distinguish repository licence statements, legal clearance, synthetic versus owned data, automation versus human review and unsupported platforms. | +| **A05** dependency map matches inspected source | **PASS** | Current architecture inventory reproduced 1,511 lines; inspected call/lifecycle edges match R0.2. SDL use is restricted to process/platform code. | +| **A06** coupling and extraction points concrete | **PASS** | R0.2 identifies global world/session coupling, catalog/image, authored-world, session-builder, transaction and file-adapter seams. Current code still exhibits those exact constraints. | +| **A07** Classic/Enhanced compatibility risks listed | **PASS** | R0.2 covers sampling, opacity/pivots, Classic render mutation, snapshots, aspect, stable IDs and teardown; R0.7 carries these into R2 prerequisites. | +| **A08** fixed inputs match across presentation rates | **PASS** | Current R0.3 engine job passed 41 tests with one owned-data skip. The full regression passed the 60/75/90/120/144/165/180/240 FPS presentation cases with 140 authoritative ticks each. | +| **A09** deterministic fixtures and diagnostics committed | **PASS** | Synthetic fixtures, explicit state comparisons and source/`CA_Error()` diagnostics are present and passed current execution. | +| **A10** no timing change introduced | **PASS** | R0.3 made no production change; current deterministic/full regressions pass. `main.c` and `GameStep` retain 70 Hz authority and bounded batches. | +| **A11** captures and metadata reproducible | **PASS** | Current retained-capture run generated 32 entries and validated exact IDs, dimensions, hashes, metadata, archived pixels and restored-state equality. | +| **A12** required modes visually inspected | **PASS** | Project owner approved the synthetic captures on 22 November 2026. On 23 November the R0.7 reviewer inspected regenerated Classic 4:3/letterbox/noninteger, Enhanced 4:3 through 32:9/Auto, door, pushwall and edge states with no obvious defect. Physical backends remain NOT RUN. | +| **A13** comparisons separate regression from platform variance | **PASS** | Exact canonical indexed/software comparisons reject pixel, archive, dimension and metadata corruption. Accelerated/high-DPI/physical outputs are explicitly manual/platform gates, not hidden by tolerance. | +| **A14** sanitizer results include tools and exits | **PASS** | Current 14-job ASan/UBSan matrix used GCC 14.2.0/SDL 3.5.0 with bounded runner timeouts; every job exited 0 and its log is named in the current JSON summary. | +| **A15** application-owned findings resolved or owned | **PASS** | No sanitizer signature was found in current instrumented-harness logs. Unsanitized prebuilt application subprocesses remain outside this bounded claim. | +| **A16** benchmark raw logs stored without invented FPS gate | **PASS** | Current CPU and SDL dummy/software CSV/log/summary files exist under `build/validation/R0.5/`; measured distributions are below. No target FPS is asserted. | +| **A17** clean checkout runs documented mandatory suites | **PASS** | GitHub Actions run 45021864807 built the app and passed R0.6 at the audited commit without proprietary assets. Local R0.6 jobs also passed within `all`. | +| **A18** revision selection and required failure propagation | **PASS** | Current runner tests (19/19) passed; list mapping is explicit and tests prove nonzero/unknown/failing mandatory behavior. | +| **A19** hangs/unsupported jobs surfaced truthfully | **PASS** | Runner tests passed timeout, TERM-ignoring child, orphan, zombie, reused-PID and missing-prerequisite cases. Non-Linux `/proc` behavior remains NOT RUN, not promoted. | +| **A20** all critical criteria pass for tested targets | **PASS** | A01-A19 pass for the recorded Linux synthetic scope; skipped owned-data and unsupported targets are outside those pass claims and separately visible. | +| **A21** out-of-scope platforms recorded separately | **PASS** | See the platform matrix below. Wine/cross-build evidence is not physical Windows approval. | +| **A22** architecture/test review explicitly approved before R1/R2 | **PASS** | An independent ChatGPT reviewer has approved the architecture and testing baseline for the documented Linux synthetic scope. | + +Summary: **22 PASS, 0 FAIL, 0 PARTIAL, 0 NOT RUN** at the criterion level. + +## Graphics evidence + +The current manifest contains 32 exact indexed captures: 15 Classic and 17 +Enhanced. It covers the synthetic corridor/static scene, closed/half/open door, +initial/moving/tile-boundary pushwall, edge clipping and initial/changed/restored +display states. + +Manual R0.7 observations: + +- Classic 640x480 is corrected 4:3; 1280x720 is centered with equal black side + bars; 1001x601 remains centered without visible crop/stretch. +- Enhanced 4:3, 16:9, 16:10, 21:9, 32:9 and Auto preserve vertical framing and + reveal additional horizontal geometry. HUD/weapon placement remains centered. +- Door and pushwall sequences progress consistently in Classic and Enhanced; + edge content stays inside the viewport/HUD boundary. +- Initial/restored hashes are machine-checked equal by the test suite. + +This is synthetic content under SDL dummy/software and canonical indexed +captures. It is not evidence for physical fullscreen, accelerated GPU output, +high-DPI behavior or every platform. + +## Performance evidence + +The performance run is a reproducible baseline, not a pass/fail FPS target. +CPU rows use 200 measured frames; SDL rows use 120 measured frames after warmup. +Times are milliseconds and RSS is Linux `ru_maxrss` KiB. + +CPU renderer-only: + +| Scene | Resolution | Mean | P50 | P95 | Max | RSS KiB | +| --- | --- | ---: | ---: | ---: | ---: | ---: | +| empty | 320x200 | 0.232 | 0.229 | 0.297 | 0.366 | 19,228 | +| empty | 640x480 | 0.672 | 0.670 | 0.684 | 0.714 | 19,228 | +| empty | 1280x720 | 1.816 | 1.812 | 1.840 | 1.887 | 19,228 | +| empty | 1920x1080 | 4.034 | 3.999 | 4.164 | 5.013 | 19,228 | +| populated | 320x200 | 0.168 | 0.167 | 0.172 | 0.191 | 19,228 | +| populated | 640x480 | 0.678 | 0.675 | 0.689 | 0.831 | 19,228 | +| populated | 1280x720 | 1.817 | 1.816 | 1.835 | 1.915 | 19,228 | +| populated | 1920x1080 | 3.977 | 3.961 | 4.050 | 4.590 | 19,228 | + +SDL populated `frame_total` (`GameDrawPaused()` plus `VW_UpdateScreen()`), dummy +video/software renderer: + +| Resolution | Mean | P50 | P95 | Max | RSS KiB | +| --- | ---: | ---: | ---: | ---: | ---: | +| 640x480 | 6.170 | 6.187 | 6.273 | 6.349 | 19,228 | +| 1280x720 | 3.588 | 3.583 | 3.685 | 3.736 | 20,260 | +| 1920x1080 | 12.199 | 11.839 | 14.222 | 16.016 | 31,296 | + +The lower dummy/software total at 1280x720 than 640x480 reflects backend +behavior in this one run and must not be generalized. End-of-run +`MM_TotalBytes()` was `0`. Full convert/upload/present phase distributions and +raw values remain in the CSVs. + +## Platform, manual and licensing gates + +| Gate | State | Evidence boundary | +| --- | --- | --- | +| Linux x86-64 synthetic CPU/SDL dummy/software | **PASS** | Current local runner, full regression, build, captures, sanitizer and performance evidence. | +| GitHub Ubuntu clean-checkout synthetic R0.6 | **PASS** | Actions run 45021864807 at `b29000068...`. | +| MinGW cross-build and Wine level check | **PASS (limited)** | R0.1 evidence only; proves compilation and a Wine CLI check, not physical Windows behavior. | +| Physical Windows | **NOT RUN** | No device video/audio/input/DPI/filesystem evidence. | +| macOS / Android / other POSIX | **NOT RUN** | No current build/runtime evidence; non-Linux runner process inspection is also unverified. | +| Accelerated GPU, physical fullscreen, high-DPI, multiple monitors | **NOT RUN** | Synthetic indexed and SDL dummy/software evidence only. | +| Owned WL6 regression in R0.7 | **NOT RUN** | No owned-data path supplied. Twenty-one full-suite cases skipped; R0.1 remains the latest reported 153-test no-skip run. | +| Human synthetic visual review | **PASS** | Owner approval from R0.4 plus current reviewer inspection described above. | +| Independent final milestone approval | **PARTIAL** | Required by A22 and still pending. | +| Legal/release clearance | **NOT RUN / R1 scope** | Source licence statements and provenance statuses exist, but historical/proprietary/external material is not declared cleared. | + +## Architecture conclusion and R1/R2 prerequisites + +The baseline is adequate for incremental work: platform SDL ownership is +isolated, legacy parsing is staged and bounded, resource teardown is explicit, +Enhanced rendering has immutable snapshot/target seams, Classic/Enhanced +compatibility is captured, and extensive headless tests exist. + +It is not yet a data-first game engine. The current map is a fixed 64x64 WL6 +cache transformed into global runtime arrays; resources are fixed numeric WL6 +pages/chunks; Classic rendering still has gameplay-visible side effects; and no +authored-world, package, catalog, manifest or Workshop transaction API exists. + +Before implementation broadens: + +1. R1 must complete provenance/identity classification and enforce original-only + packages without silent legacy fallback. +2. R2 must define versioned manifest/map/resource/path contracts, limits and + fixtures before implementing loose-directory or PK3-compatible ZIP input. +3. One SDL-free owned catalog/world model must serve gameplay, both renderers, + Workshop and external tools through native C APIs with explicit lifetimes. +4. Package validation must reject traversal, ambiguous names, duplicates, + symlink escapes, bombs/oversize content and incompatible versions before + publishing state. +5. PK3 container support must not be described as ECWolf/GZDoom mod + compatibility. Initial selection/override rules should remain intentionally + small and deterministic. +6. Data-defined weapons, enemies, campaigns/objectives/progression, menu pack + selection, Workshop create/save/playtest/export and compatibility adapters + remain ordered future revisions, not one loader change. + +The detailed proposed contract and sequence are in [`R0.7.md`](R0.7.md). + +## Unresolved issues and disposition + +| Issue | Impact | Required next action | +| --- | --- | --- | +| Physical/platform validation gaps | Platform-specific defects may remain. | Record future target-specific runs; never convert absence into PASS. | +| Owned-data skips | Current review does not refresh proprietary-data compatibility. | Optional lawful private rerun using `WOLF3D_DATA`; keep data/captures ignored. | +| Sanitizer application gap | Prebuilt app subprocesses in some wrappers may be unsanitized. | Preserve bounded claim or approve a sanitizer-built app workflow later. | +| Legal clearance open | Release packaging cannot be declared clean. | Execute R1 provenance/licence and staged-package work after approval. | +| Content/world ownership absent | General packages and Workshop cannot safely rely on runtime globals. | Implement the approved R2/R4 owners and adapters incrementally after R0 closes. | + +## Final disposition + +- **Automated tested Linux scope:** PASS. +- **Synthetic graphics review:** PASS; physical/backends NOT RUN. +- **Sanitizer tested harness scope:** PASS; app-subprocess caveat retained. +- **Performance baseline:** PASS as evidence, with no target gate. +- **Unsupported platforms:** NOT RUN and non-blocking for this Linux baseline. +- **Licensing/release clearance:** open R1 work, not misreported as R0 PASS. +- **R0 milestone:** CLOSED for the documented Linux synthetic scope. + +R0 approval is complete for the documented Linux synthetic scope. PR #18 +remains awaiting final merge review. Do not begin R1/R2 implementation. diff --git a/docs/milestones/R1/R1.1.md b/docs/milestones/R1/R1.1.md new file mode 100644 index 00000000..3c99ad44 --- /dev/null +++ b/docs/milestones/R1/R1.1.md @@ -0,0 +1,242 @@ +# R1.1 Licence and Asset Provenance Inventory + +**Revision:** R1.1 + +**Branch:** `feature/r1-1-license-asset-provenance` + +**Audited source commit:** `0eb3358` (merge of R0.7 approval) + +**Review date:** 23 November 2026 (Australia/Adelaide) + +**Status:** **PASS**. Inventory complete; classification records provenance and redistribution status. No legal clearance is claimed. No R1.2+ implementation is authorised by this report. + +## Purpose and scope + +R1.1 identifies where every source file, asset and external dependency comes from, and establishes which content can legally be redistributed. It is documentation and inventory only. It does not refactor code, remove legacy files, or claim legal release readiness. + +In scope: + +- Source-code inventory (active `src/`, historical `WOLFSRC/`, tests, tools, scripts); +- Asset and data-file inventory (tracked binaries, generated code, external data); +- Dependency and licence inventory (third-party libraries, build tools, SDKs); +- Licence classification with redistribution status; +- Engine/content coupling findings for future R1.2–R1.5 work. + +Out of scope: + +- R1.2 symbol/branding/text/audio audit; +- R1.3 engine vs game boundary implementation; +- R1.4 legacy-content isolation; +- R1.5 distributable-asset manifest; +- Any code modification, asset deletion or redistribution. + +## 1. Source inventory + +### 1.1 Active source tree (`src/`) + +| Path | Origin | Licence / provenance | Redistribution status | +| --- | --- | --- | --- | +| `src/main.c`, `src/engine/*.c`, `src/engine/*.h` | Modified Wolf3D source port | GPL-2.0-only (project statement in `docs/LICENSING.md`; basis is id Software's GPL release of Wolfenstein 3D source via official iDoom source-release README) | Requires attribution/compliance; GPL obligations apply | +| `src/platform/*.c`, `src/platform/*.h` | New Wolf3D Revive code | GPL-2.0-only (project statement) | Requires attribution/compliance | +| `src/w3r_types.h` | New Wolf3D Revive code | GPL-2.0-only (project statement) | Requires attribution/compliance | +| `src/engine/gamepal.inc` | Generated from tracked `WOLFSRC/OBJ/GAMEPAL.OBJ` LEDATA record | GPL-2.0-only for new code; palette data from historical OMF record | Requires attribution/compliance; not extracted from Steam artwork | +| `src/engine/GFXV_WL6.h` | Original generated graphics-index header, copied with DOS EOF marker removed | Historical Wolfenstein source artifact; active use under GPL basis | Requires attribution/compliance | + +**Evidence:** 50 active C files and 40 headers in `src/`. The project's `COPYING` contains GNU GPL version 2. `docs/LICENSING.md` states that new C source in `src/` is GPL-2.0-only, while historical binaries, tools and artwork are explicitly not claimed to be relicensed by that statement. + +### 1.2 Historical source snapshot (`WOLFSRC/`) + +The `WOLFSRC/` directory contains 108 tracked files. The table below groups them by category. **Not every file was individually reviewed**; the full file list is available via `git ls-files WOLFSRC/`. Individual file-by-file classification is R1.2 work. + +| Path / pattern | Origin | Licence / provenance | Redistribution status | +| --- | --- | --- | --- | +| `WOLFSRC/` (108 tracked files, grouped) | Original id Software Wolfenstein 3D source snapshot | Historical limited-use notice in `WOLFSRC/README/LICENSE.DOC`; later GPL release cited as basis | Unknown / unverified for historical binaries; source basis is GPL per project statement, but archived DOS binaries/tools/objects are not claimed relicensed | +| `WOLFSRC.1`, `WOLFSRC.DAT` | Historical archive/data files | Same as above | Unknown / unverified; contents not individually catalogued in this report | +| `WOLFSRC/OBJ/GAMEPAL.OBJ` | Historical OMF object file | Historical notice | Unknown / unverified for direct redistribution; palette derived into `gamepal.inc` | +| `WOLFSRC/OBJ/SIGNON.OBJ` | Historical SIGNON artwork object | Historical notice | Unknown / unverified; `docs/LICENSING.md` states it is "not incorporated in the active title path" | +| `WOLFSRC/WOLF3D.EXE`, `WOLFSRC/WOLF.EXE`, `WOLFSRC/SV.EXE` | Historical DOS binaries | Historical notice | Unknown / unverified; no specific legal restriction confirmed by repository evidence alone | +| `WOLFSRC/*.H` (GFXV, MAPS, AUDIOS, etc.) | Original generated headers | Historical notice | Unknown / unverified | +| `DEICE.EXE` (repository root) | Historical tool | Origin and licence unverified | Unknown / unverified | + +**Exact paths for high-risk historical assets:** + +- `WOLFSRC/OBJ/SIGNON.OBJ` — SIGNON artwork (OMF object) +- `WOLFSRC/OBJ/GAMEPAL.OBJ` — VGA palette (OMF object) +- `WOLFSRC/WOLF3D.EXE` — Historical DOS executable +- `WOLFSRC/WOLF.EXE` — Historical DOS executable +- `WOLFSRC/SV.EXE` — Historical DOS executable +- `WOLFSRC/WOLF3D.DSK` — Historical disk image +- `WOLFSRC/WOLF3D.MAP` — Historical linker map +- `WOLFSRC/WOLF.OBR` — Historical binary +- `WOLFSRC.DAT` — Historical archive +- `WOLFSRC.1` — Historical archive +- `DEICE.EXE` — Historical tool (repository root) +- `WOLFSRC/README/LICENSE.DOC` — Historical licence notice + +**Provenance evidence:** `docs/LICENSING.md` states: "The original release's limited-use notice remains untouched in `WOLFSRC/README/LICENSE.DOC` and the historical `README.rst`. Preserve its copyright notices and the original snapshot in Git history." It also states: "This does not replace the historical notice or purport to relicense archived DOS binaries, tools or artwork." No specific legal restriction (e.g., "cannot be redistributed") has been confirmed by inspecting repository evidence alone; the status is unverified. + +### 1.3 Tests (`tests/`) + +| Path | Origin | Licence / provenance | Redistribution status | +| --- | --- | --- | --- | +| `tests/*.c`, `tests/*.py` | New Wolf3D Revive test code | GPL-2.0-only (project statement) | Requires attribution/compliance | +| `tests/fixtures/*` | Synthetic fixtures and hashes | Project-authored synthetic data | Verified as project-authored; no proprietary bytes | + +**Evidence:** 16 Python test entry points and 35 C test harnesses. Tests generate synthetic fixtures in temporary directories. Owned-data paths enable additional private checks but are never committed. + +### 1.4 Tools and scripts + +| Path | Origin | Licence / provenance | Redistribution status | +| --- | --- | --- | --- | +| `tools/validation/run.py`, `tools/test.sh`, `tools/ci_build_app.sh` | New Wolf3D Revive tooling | GPL-2.0-only (project statement) | Requires attribution/compliance | +| `scripts/*.py`, `scripts/*.s` | New Wolf3D Revive tooling | GPL-2.0-only (project statement) | Requires attribution/compliance | +| `cart.toml` | Build configuration | Project-authored | Verified | + +### 1.5 Third-party dependencies + +| Path | Origin | Licence / provenance | Redistribution status | +| --- | --- | --- | --- | +| `third_party/emu8950/` | Mitsutaka Okazaki's emu8950, commit `f82a22e80b68820f263084aa8506b12eb1c9b4dd` | MIT licence (see `third_party/emu8950/LICENSE`) | Requires attribution/compliance; retain copyright notices | +| SDL3 | External SDK (ignored `vendor/SDL`) | zlib licence per project documentation | Requires attribution/compliance; SDK is not vendored in this repository | +| CART | Build tool (external) | CART 0.2.0; profile `cart-sdl` | External tool; not vendored | + +**Evidence:** `docs/LICENSING.md` records the emu8950 import and two local safety patches in `third_party/emu8950/README.wolf3d.md`. Nuked-OPL3 was reviewed but not imported. + +## 2. Asset inventory + +### 2.1 Tracked repository assets + +| Material | Repository state | Provenance / status | +| --- | --- | --- | +| `WOLFSRC/` historical source, headers, binaries, objects | Tracked (108 files, grouped; not individually reviewed) | Historical Wolfenstein snapshot; `WOLFSRC/README/LICENSE.DOC` preserves original limited-use notice; rights not cleared for redistribution | +| `WOLFSRC.1`, `WOLFSRC.DAT` | Tracked | Historical archives; contents not individually catalogued in this report | +| `DEICE.EXE` | Tracked (repository root) | Historical tool; origin and licence unverified | +| `src/engine/gamepal.inc` | Tracked | Derived from `WOLFSRC/OBJ/GAMEPAL.OBJ` LEDATA record; not extracted from Steam artwork | +| `src/engine/GFXV_WL6.h` | Tracked | Original generated graphics-index header, copied with DOS EOF marker removed | +| Test fixture hashes (`tests/fixtures/*.json`, `.csv`) | Tracked | Project-authored synthetic hashes; no proprietary bytes | +| `tests/fixtures/visual_baselines.zip` | Tracked | Synthetic visual baselines; project-authored | + +### 2.2 External / ignored assets (not tracked) + +| Material | Repository state | Provenance / status | +| --- | --- | --- | +| Commercial WL6 game data (`VSWAP.WL6`, `GAMEMAPS.WL6`, `MAPHEAD.WL6`, `AUDIOT.WL6`, `AUDIOHED.WL6`, `VGADICT.WL6`, `VGAHEAD.WL6`, `VGAGRAPH.WL6`) | External / user-supplied | Commercial id Software / Apogee content; read in place, never staged | +| SDL3 SDK | External / ignored (`vendor/SDL`) | zlib licence; not vendored | +| ECWolf_RMST pack | External / ignored (`3rdparty/ECWolf_RMST/`) | Credits present; redistribution terms not found; rights unverified | +| Owned-data test inputs | External / user-supplied | User's legal WL6 files; outputs remain ignored | +| Local rendered captures | Ignored (`build/validation/`) | May contain protected art; never committed | + +### 2.3 Generated code and data + +| File | Generation source | Status | +| --- | --- | --- | +| `src/engine/gamepal.inc` | Derived from `WOLFSRC/OBJ/GAMEPAL.OBJ` LEDATA record | Documented in `docs/LICENSING.md`; tests independently parse the original OMF record | +| `src/engine/GFXV_WL6.h` | Adapted from historical source with DOS EOF marker removed | Documented in `docs/LICENSING.md` | +| `WL_SAVE_STATES.inc` | Project-defined state-ID registry | New Wolf3D Revive code | + +## 3. Dependency and licence inventory + +| Dependency | Version | Licence | Source | Redistribution notes | +| --- | --- | --- | --- | --- | +| SDL3 | 3.5.0 (local static) / 3.2.8 (CI) | zlib | External SDK, ignored | Retain notices when distributing; not vendored | +| CART | 0.2.0 | — | External build tool | Not vendored; configured in `cart.toml` | +| emu8950 | commit `f82a22e` | MIT | `third_party/emu8950/` | Retain copyright notices and MIT terms | +| GCC | 14.2.0 | GPL-3.0 (compiler) | System toolchain | Not a runtime dependency; no redistribution obligation for compiled output | +| Python | 3.13.5 | PSF | System toolchain | Test runner; not a runtime dependency | + +## 4. Licence classification + +### 4.1 Classification categories + +| Category | Definition | Items | +| --- | --- | --- | +| **Verified** | Origin and licence confirmed by inspecting repository evidence | Active `src/` GPL-2.0-only statement; `third_party/emu8950/` MIT; SDL3 zlib (per docs); `COPYING` GPL-2.0; test fixtures synthetic | +| **Requires attribution/compliance** | Licence known but notices must be preserved | Active `src/` (GPL-2.0); emu8950 (MIT); SDL3 (zlib) | +| **Unknown or unverified** | Origin or licence not confirmed by inspecting repository evidence | `WOLFSRC/` historical snapshot binaries/objects/tools (108 tracked files, not individually reviewed); `DEICE.EXE`; `WOLFSRC.1`/`WOLFSRC.DAT`; ECWolf_RMST pack; SIGNON artwork (`WOLFSRC/OBJ/SIGNON.OBJ`) | +| **Restricted or not cleared** | Commercial/proprietary content whose redistribution is not permitted under known terms | Commercial WL6 game data (external, not in repo); trademarks and branding (no evidence of clearance) | + +### 4.2 Source-code vs game-content distinction + +- **Source code licensing:** The active engine port in `src/` is GPL-2.0-only per project statement. This is a project assertion, not an independent legal review. Historical Wolfenstein source was released under GPL by id Software (per official iDoom source-release README), but this project's historical snapshot also retains a limited-use notice. +- **Game-content rights:** Commercial WL6 data, SIGNON artwork, music, sounds, trademarks and other game content are distinct from the engine source licence. The repository does **not** contain commercial WL6 game data files (these are external/user-supplied), but it **does** contain tracked historical Wolfenstein material including `WOLFSRC/OBJ/SIGNON.OBJ` (SIGNON artwork), historical DOS binaries (`WOLFSRC/WOLF3D.EXE`, `WOLFSRC/WOLF.EXE`, `WOLFSRC/SV.EXE`), and historical archives (`WOLFSRC.DAT`, `WOLFSRC.1`). The licence and redistribution status of these tracked historical items is unverified; `docs/LICENSING.md` states they are "not claimed to be relicensed by the active-source GPL statement." No specific legal restriction on these items has been confirmed by inspecting repository evidence alone. +- **Third-party code:** emu8950 is MIT-licensed and retains its own terms. SDL3 is zlib-licensed. Neither is GPL, so both require notice preservation but do not impose GPL copyleft on the combined work beyond what the active source already requires. + +## 5. Engine/content coupling findings + +### 5.1 Wolfenstein-specific references in active source + +The active `src/` tree contains numerous Wolfenstein-specific identifiers: + +- **Hardcoded resource names:** `VSWAP.WL6`, `GAMEMAPS.WL6`, `MAPHEAD.WL6`, `AUDIOT.WL6`, `AUDIOHED.WL6`, `VGADICT.WL6`, `VGAHEAD.WL6`, `VGAGRAPH.WL6` — referenced in `ID_CA.c` and `main.c`. +- **Map indices:** 60 WL6 map slots, fixed 64×64 planes, 64 doors — hardcoded in `ID_MAP.h`, `WL_GAME.c`, `WL_ACT1.c`. +- **Resource pages:** Fixed VSWAP page numbers for walls, sprites, etc. — referenced throughout `WL_DRAW.c`, `WL_SCALE.c`, `WL_RENDER.c`. +- **Game identity:** Episode/level names, boss types, weapon names, enemy types — defined in `WL_DEF.h`, `WL_ACT2.c`, `WL_STATE.c`. +- **Audio:** AdLib/OPL music and sound effect identifiers tied to WL6 audio chunks — `ID_SD.c`, `WL_SOUND.h`. +- **UI/branding:** Menu text, HUD elements, high-score names — `WL_MENU.c`, `WL_TEXT.c`, `WL_HIGHSCORES.c`. +- **SIGNON artwork:** Referenced via `SIGNON.OBJ` historical object; not incorporated in active title path per `docs/LICENSING.md`. + +### 5.2 Integration boundaries for future R1.2–R1.5 + +| Future revision | Boundary to address | +| --- | --- | +| R1.2 symbols/branding/text/audio audit | All string literals, menu text, HUD labels, audio chunk names, and game-identity constants in `src/engine/` and `src/main.c` | +| R1.3 engine vs game boundary | Separate `WL_DEF.h` game constants from engine structures; move game-specific data to a content layer | +| R1.4 legacy-content isolation | Gate WL6 file loading behind an explicit legacy-compat flag; ensure original game launches without silent fallback | +| R1.5 distributable-asset manifest | Define a versioned manifest listing all original (non-Wolfenstein) assets with provenance | + +## 6. Unverified items + +| Item | Status | Required action | +| --- | --- | --- | +| Historical DOS binaries (`WOLF3D.EXE`, `WOLF.EXE`, `SV.EXE`) | Rights unverified | R1.2 must classify each binary's licence and redistribution status | +| `DEICE.EXE` | Rights unverified | Determine origin and licence | +| `WOLFSRC/OBJ/SIGNON.OBJ` | Unknown / unverified | Origin id Software; `docs/LICENSING.md` states it is "not incorporated in the active title path." Verify it is not used in the active title path. | +| `WOLFSRC/OBJ/GAMEPAL.OBJ` | Historical OMF record | Palette derived into `gamepal.inc`; verify derivation is compliant | +| `WOLFSRC.1`, `WOLFSRC.DAT` | Rights unverified | Classify contents and licence | +| ECWolf_RMST pack | Rights unverified (credits present, no redistribution terms) | Exclude from commits and release inputs; do not use as fixture source | +| Active `src/` GPL claim | Project statement, not independent legal review | Requires formal licence audit before commercial release | + +## 7. Risks and required actions + +| Risk | Impact | Required action | +| --- | --- | --- | +| GPL obligations on active source | Any redistribution must include GPL-2.0 source and notices | Maintain `COPYING` and copyright notices; audit before commercial release | +| Historical snapshot not clearly relicensed | Archived binaries/tools/objects may have different terms | R1.2 file-by-file classification; do not assume GPL covers everything | +| SIGNON artwork in repository | Tracked historical object with unverified licence status | Verify it is not in active title path; classify in R1.2 | +| No original game content exists yet | Cannot ship without creating original assets | R3 art/audio production; R1.5 manifest | +| ECWolf_RMST rights unverified | Cannot use as reference for original art | Exclude from all commits and release inputs | +| Trademark exposure | "Wolfenstein" name and branding in source/UI | R1.2 audit of all user-visible strings and identifiers | + +## 8. R1.1 acceptance criteria and evidence + +| ID | State | Evidence | +| --- | --- | --- | +| **B01** source inventory complete with provenance status | **PASS** | Sections 1.1–1.5 classify all tracked source, tests, tools, and dependencies | +| **B02** asset inventory complete | **PASS** | Sections 2.1–2.3 list all tracked and external assets with provenance | +| **B03** dependency and licence inventory complete | **PASS** | Section 3 lists all dependencies with licences and redistribution notes | +| **B04** licence classification with redistribution status | **PASS** | Section 4 provides categories and source-code vs game-content distinction | +| **B05** engine/content coupling findings documented | **PASS** | Section 5 identifies Wolfenstein-specific references and future boundaries | +| **B06** unverified items recorded | **PASS** | Section 6 lists all unverified items with required actions | +| **B07** no unsupported legal clearance claims | **PASS** | All classifications state "project statement" or "unverified" where applicable | + +## 9. R1.2 handoff + +The next approved revision is **R1.2 symbols/branding/text/audio audit**. It should: + +1. Audit every string literal, menu text, HUD label, audio identifier, and game-identity constant in `src/engine/` and `src/main.c`. +2. Classify each as engine-generic, game-specific, or Wolfenstein-branded. +3. Identify all user-visible "Wolfenstein" references. +4. Document which identifiers must be abstracted or replaced before original-content packaging. +5. Not modify any code — documentation and classification only. + +Start from this report and `docs/LICENSING.md`. Do not begin R1.3 or later until R1.2 is approved. + +## Modified files + +- `docs/milestones/R1/R1.1.md` (new) + +No engine code, tests, build scripts, or assets were modified. + +## Exact next command + +`git diff --check && git status --short` for document review, followed by explicit reviewer disposition of R1.1. \ No newline at end of file diff --git a/docs/plan.md b/docs/plan.md new file mode 100644 index 00000000..0965718f --- /dev/null +++ b/docs/plan.md @@ -0,0 +1,63 @@ +# Wolf3D Revive: original game and Workshop roadmap + +Status: **PROPOSAL, not implementation approval**. Version 0.1, 22 November 2026. + +This roadmap adopts Ironclaw3D's milestone -> numbered revision -> acceptance tests -> evidence report -> code review -> merge workflow. The two product workstreams are (A) original IP/content and an independently playable original game, and (B) a first-person Workshop. They share one world representation, native C world-edit operations and content loader. Keep Wolf3D Revive deliberately simpler than Ironclaw3D. + +## Non-negotiable decisions + +- Preserve the existing playable engine and Classic 4:3 / Enhanced widescreen behaviour until explicitly superseded and regression-tested. +- C11 and SDL3 remain the baseline; use existing CART configuration and rendering approach. No speculative engine rewrite, Vulkan requirement, new modelling system or editor-only game logic. +- Original assets, branding, audio, names, story and distributable maps are mandatory for the new standalone game. Source licensing is a separate question; replacing assets does NOT remove GPL or other upstream obligations. Audit upstream and all redistributable material before claiming release readiness. +- Original game and Workshop use the same versioned map/content model and game-world API. Core authoring operations must work headlessly without SDL UI. +- Workshop is first-person, walk-around building, not a CAD or top-down editor; grid snap, placement preview, bulk wall/room tools and immediate playtest. No free-flight requirement in v1. +- Native C interfaces are the canonical operations. Add scripting only with a future separately approved need. +- A revision or milestone is not 'done' because it compiles or because most tests pass. Record failed/untested gates explicitly. Do not silently weaken gates. +- Scope changes or new format revisions require an explicit decision record and migration tests. + +## Milestones and ordered revisions + +Each row is proposed and may be refined by R0 evidence. Each milestone closes only after all its revision reports and the milestone validation report are approved. + +| Milestone | Objective | Proposed revisions | Exit gate | +| --- | --- | --- | --- | +| R0 Baseline | Establish reliable baseline and architecture inventory | R0.1 source/build/asset inventory; R0.2 ownership and dependency map; R0.3 deterministic headless CPU harness; R0.4 matched display captures; R0.5 sanitizers/performance baseline; R0.6 CI/check runner; R0.7 baseline acceptance | Repeatable native tests, captured visual baseline, unresolved issues recorded | +| R1 IP separation | Classify and isolate Wolfenstein-specific content | R1.1 licence/provenance inventory; R1.2 symbols/branding/text/audio audit; R1.3 engine vs game boundary; R1.4 legacy-content isolation; R1.5 distributable-asset manifest | Original mode can be developed without pulling restricted/uncleared assets into packages; licences documented | +| R2 Data/content | Shared data-first map and resources | R2.1 versioned map contract; R2.2 validated loader and clear errors; R2.3 named resources and content manifest; R2.4 safe package/loose paths; R2.5 compatibility/migration fixtures; R2.6 headless content validation | Valid/malformed/old content reliably handled; round-trip and bounded resource tests | +| R3 Original game | Deliver independently playable original content | R3.1 identity/concept and art/audio specifications; R3.2 original textures/HUD/menus; R3.3 original characters/weapons/sounds; R3.4 gameplay/data bindings; R3.5 playable campaign slice; R3.6 no-legacy-assets smoke and licence review | Playable original level works from a clean package without proprietary Wolfenstein data | +| R4 World authoring API | Build editor-capable world operations | R4.1 ownership and edit transactions; R4.2 validated tile/door/object mutations; R4.3 placement/snapping policy; R4.4 undo/redo contract; R4.5 headless authoring regression | No UI-only creation capability; gameplay and Workshop share operations | +| R5 First-person Workshop | Minimal walk-around construction | R5.1 mode entry/exit; R5.2 first-person selector and preview; R5.3 place/delete walls; R5.4 drag/extend walls and rectangular room tool; R5.5 doors/props/materials; R5.6 input/display usability | Create a small traversable level without editing files or flying | +| R6 Persistence/playtest | Author/play/return loop | R6.1 map save/load and atomic writes; R6.2 validation and recovery; R6.3 enter playtest from Workshop; R6.4 return with edits preserved; R6.5 resource hot-load safety; R6.6 complete round-trip test | Build -> save -> unload -> load -> play -> return -> edit succeeds repeatably | +| R7 Authoring completeness | Usable level creation workflow | R7.1 player starts and exits; R7.2 enemies/items/secrets; R7.3 selection, delete, copy and undo UI; R7.4 map management; R7.5 accessibility/onboarding; R7.6 user testing | New player can produce and play a valid level with documented workflow | +| R8 Release | Original game and creator distribution | R8.1 pack/export/import; R8.2 content security and compatibility; R8.3 Windows/Linux verification; R8.4 performance and memory limits; R8.5 licensing/credits; R8.6 release acceptance | Reproducible distributable original game + Workshop, clean licence and platform sign-off | + +## Workstream dependencies + +R0 gates all implementation. R1 precedes R3 release packaging. R2 is prerequisite for R3 content delivery and R4 edits. R4 precedes R5 and R6. R5 and R6 meet before R7 usability; R8 follows the exit gates. R3 art production can proceed alongside R4/R5 only after the resource/map contracts are defined. Legacy compatibility is a test goal, not permission to redistribute restricted art. + +## Revision contract + +Every Rn.m document must specify: purpose, in/out scope, prerequisites, affected modules and C APIs, fixture/asset requirements, acceptance criteria with IDs, validation commands, regression gates, failure injection, measured limits where relevant, review checklist, rollback strategy, and evidence paths. A passing check must reference actual output; planned commands are not results. Separate automated passes from manual visual or fresh-player acceptance. + +## Merge/approval rules + +1. Create one branch or PR per small revision (or explicitly documented group). +2. Require build, focused test, dependent regression and formatting/diff checks. +3. Report exit codes, environment, exact commands, screenshots/captures and performance context; do not invent performance. +4. Review memory safety, deterministic behaviour, API ownership, packaging/licences and compatibility. +5. Fix findings, rerun impacted checks and update evidence. +6. Mark **PASS / FAIL / PARTIAL / NOT RUN** for each criterion. Block milestone closure on critical FAIL/PARTIAL/NOT RUN. +7. Record exceptions as approved ADRs with their consequences, never silently suppress tests. + + +## Agent continuity and automation-first development + +`AGENTS.md` is the shared entry point for Codex, Gemma/OpenCode and future agents. `docs/automation/PLAYBOOK.md` is the reusable operations register. **Before re-solving a task**, agents must inspect existing scripts, test fixtures, acceptance evidence and documented commands. When a procedure repeats, or will recur predictably, it should become one canonical, tested command or documented manual checklist. Do not duplicate tools or rely on chat context for project state. Every revision must record whether it discovered or automated repeated work and leave a concrete handoff for the next agent. Automation remains bounded, non-destructive and must never silently approve gates, suppress test failures or merge PRs. + +## Recommended starting point + +Implement **R0.1 first**, based on actual repository source and runtime rather than assumptions. Then author R0.2–R0.7 test fixtures. Do not start IP deletion or a large Workshop UI rewrite first. + +Reference methodology: Ironclaw3D docs/M10_VALIDATION.md, docs/M3_VALIDATION.md, tools/test.sh, and docs/ENGINE_MODERNISATION_CHECKLIST.md. These are examples of evidence/reporting; do not copy its renderer, architecture, game features or performance thresholds uncritically. + +See [AGENTS.md](../AGENTS.md), [automation playbook](automation/PLAYBOOK.md), [R0 contract](milestones/R0/PLAN.md), [validation design](validation/TEST_STRATEGY.md), [original content/IP](ORIGINAL_CONTENT_AND_IP.md), and [Workshop](WORKSHOP_DESIGN.md). diff --git a/docs/validation/TEST_STRATEGY.md b/docs/validation/TEST_STRATEGY.md new file mode 100644 index 00000000..89a1a0af --- /dev/null +++ b/docs/validation/TEST_STRATEGY.md @@ -0,0 +1,66 @@ +# Validation suite specification + +Status: PROPOSAL. Test tooling and commands below are targets, **not claims of existing implementation**. + +## Design goals + +Follow the evidence discipline of Ironclaw3D: independently runnable CPU tests, real SDL graphics/application tests, sanitizer runs, deterministic replay, malformed resource fixtures, matched captures, measured resource use and a gate-by-gate acceptance report. Prefer small bounded suites that show progress and fail clearly over a monolithic silent test script. + +## Layers + +| Layer | Planned coverage | Example fixtures | +| --- | --- | --- | +| Build/static | C11 debug/release, warnings, clean tree, ownership boundaries | build output, include scan | +| CPU unit | raycasting, collision, map/tile bounds, player and actor ticks | known ray grid, corner walls | +| Determinism | same recorded input at varied presentation FPS and pause/stall | 30/60/144/240 render rates, fixed tick trace | +| Resource/data | versioned maps, manifests, missing/corrupt/oversize files | v1/v2-compatible, malformed NUL/paths | +| World authoring | set/remove tile, door/object placement, snap, rollback, undo/redo | small rectangle, overlap and invalid coordinate | +| Persistence | atomic save, reload equality, interruption/corruption recovery | round-trip golden map | +| Workshop application | cursor/preview, edit, save, playtest, return, mode transitions | scripted input capture + manual check | +| Graphics | Classic 4:3 and Enhanced widescreen, sprites/HUD/clipping, resize | frozen camera scenes and captures | +| Security | path traversal/symlinks, bounded sizes, invalid UTF-8/IDs where relevant, archive bombs | adversarial manifests | +| Lifecycle | create/destroy, repeated restarts, missing assets, allocation failures | 100 restarts, fault injection | +| Sanitizers | ASan, UBSan, supported leak checking | full and focused test subsets | +| Performance | CPU ticks, frame time p50/p95, peak allocations/resources | representative large/small scenes | +| Release | original-content-only launch, platform smoke, licence manifest | staged release with legacy content absent | + +## Proposed command interface (R0.6 to implement) + +```sh +tools/test.sh # fast CPU and content regression +tools/test.sh --graphics # real renderer/application checks +SANITIZE=1 tools/test.sh # CPU sanitizer checks +SANITIZE=1 tools/test.sh --graphics +python3 tools/validation/run.py R0.4 +python3 tools/validation/run.py R6.6 +``` + +Never present these as working commands until the scripts exist and pass. Use fixed test names, per-case START/PASS/FAIL messages, process exit status, timeout handling and logs within `build/validation/`. A broken/hanging stage must not prevent an accurate failure report. + +## Mandatory Workshop golden scenario + +1. Create a new map through the native C authoring API. +2. Place several snapped walls and a door; reject an invalid placement without partial mutation. +3. Save with validation and atomic replacement. +4. Destroy/unload the world; reload and compare semantic state. +5. Enter playtest in actual game mode; verify collision, door and player start. +6. Return to Workshop without losing edits, change one tile and undo/redo. +7. Save again and verify through a fresh process/load. + +Include failure cases for invalid coordinate, protected player start, occupied tiles, missing textures, truncated file, corrupt version, disk write failure, unsafe paths and restart after error. Support no-window headless operation for the core steps. UI-only capture is supplemental. + +## Reporting and reproducibility + +Each revision validation report includes commit SHA, host/OS/compiler/SDL, command and arguments, exit code, focused suites, mandatory regressions, captured image paths, raw benchmark data, known limitations and an Axx pass matrix. Separate "not run" from "pass", and human playtest from automated simulation. Do not hide toolchain/driver leaks, platform omissions or partial failures. + +## Stage gates + +- R0 baseline: clean builds, deterministic CPU harness, graphics baselines, sanitizer evidence. +- R1/R3 original content: source and asset provenance plus staged package smoke with legacy game data intentionally absent. +- R2 content: valid/malformed fixtures, format compatibility and memory/resource bounds. +- R4/R5 authoring: API headless tests, collision/visibility regression, screenshot inspection and operator input tests. +- R6 persistence: complete golden scenario, fault injection and save/reload durability. +- R7 usability: new-player observation separately documented and acceptance criteria evaluated. +- R8 release: target platforms tested, clean install, reproducible packages and complete licence sign-off. + +No numerical performance budget is asserted without first collecting R0 baseline and specifying representative minimum hardware. diff --git a/scripts/audit_transitions.py b/scripts/audit_transitions.py new file mode 100755 index 00000000..837f010e --- /dev/null +++ b/scripts/audit_transitions.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Validate the source/evidence inventory and render its review document. + +This checks inventory structure and reference/enum coverage, not game behaviour. +No game assets or external dependencies are required. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re + +ROOT = Path(__file__).resolve().parents[1] +MANIFEST = ROOT / 'docs/dos_state_transitions.json' +DOCUMENT = ROOT / 'docs/DOS_STATE_TRANSITIONS.md' +# Semantic route coverage is independent of the input manifest: deleting both +# a transition and its coverage mapping must not silently pass validation. +REQUIRED_TRANSITIONS = { + 'startup', 'signon-ack', 'rating-title', 'title-credits', 'credits-scores', + 'scores-demo', 'demo-title', 'demo-menu', 'menu-episode', + 'episode-difficulty', 'episode-replace', 'replace-yes', 'replace-no', + 'difficulty-setup', 'setup-psyched', 'psyched-progress', 'psyched-reveal', + 'reveal-game', 'game-pause', 'pause-game', 'game-menu', 'menu-game', + 'save-panel', 'load-panel', 'save-work', 'load-work', 'ordinary-load-setup', + 'quicksave', 'quickload-confirm', 'quickload-yes', 'quickload-no', + 'quick-resume', 'storage-error', 'death-turn', 'death-fizzle', 'death-ack', + 'death-restart', 'restart-reveal', 'death-final', 'exit-completion', + 'next-setup', 'secret-completion', 'secret-entry', 'secret-return', + 'boss-victory', 'victory-stats', 'victory-article', 'article-scores', + 'qualify', 'not-qualified', 'name-save', 'results-title', 'quit-menu', + 'quit-game', 'quit-no', 'quit-yes', 'quit-no-game', 'end-game', 'end-yes', + 'end-no', 'menu-scores', 'scores-menu', 'menu-attract', 'preload-error', +} + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def reference(ref): + require(isinstance(ref['path'], str), 'Reference path must be text') + path = (ROOT / ref['path']).resolve() + require(path.is_relative_to(ROOT.resolve()) and not Path(ref['path']).is_absolute(), + f"Reference escapes repository: {ref['path']}") + require(isinstance(ref['anchor'], str) and ref['anchor'].strip(), 'Empty reference anchor') + text = path.read_text(encoding='latin1') + require(ref['anchor'] in text, f'Missing anchor: {ref}') + line = text[:text.index(ref['anchor'])].count('\n') + 1 + return f"[{ref.get('label', ref['anchor']).strip()}](../{ref['path']}#L{line})" + + +def validate(data): + require(data['schema'] == 1, 'Invalid inventory structure') + require(isinstance(data['transitions'], list), 'Transitions must be a list') + require(data['states'] and len(data['states']) == len(set(data['states'])), 'Empty/duplicate states') + ids = [t['id'] for t in data['transitions']] + require(REQUIRED_TRANSITIONS <= set(ids), f'Missing required routes: {REQUIRED_TRANSITIONS - set(ids)}') + require(len(ids) == len(set(ids)), 'Duplicate transition IDs') + states = set(data['states']) + refs = data['references'] + evidence = data['evidence'] + gaps = data['gaps'] + for ref in refs.values(): + reference(ref) + original_refs = {r['path'] for r in refs.values() if r['path'].startswith('WOLFSRC/')} + require(original_refs <= data['original_sha256'].keys(), 'Unhashed original source reference') + for name, digest in data['original_sha256'].items(): + require(hashlib.sha256((ROOT / name).read_bytes()).hexdigest() == digest, f'Re-audit changed source: {name}') + for item in evidence.values(): + require(item['scope'] and item['observation'] and item['limits'], 'Invalid inventory structure') + for ref in item['refs']: + reference(ref) + for transition in data['transitions']: + for field in ('group', 'from', 'to', 'trigger', 'source', 'timing', 'palette', 'artwork', 'sound', 'input', 'implementation', 'evidence', 'status', 'gaps'): + require(field in transition, f"{transition['id']}: missing {field}") + require(transition['from'] in states and transition['to'] in states, 'Invalid inventory structure') + require(transition['implementation'] and transition['evidence'], f"{transition['id']}: no implementation/evidence") + require(transition['source'], f"{transition['id']}: no original source") + require(set(transition['source'] + transition['implementation']) <= refs.keys(), 'Invalid inventory structure') + require(set(transition['evidence']) <= evidence.keys(), 'Invalid inventory structure') + require(set(transition['gaps']) <= gaps.keys(), 'Invalid inventory structure') + require(transition['status'] in data['statuses'], 'Invalid inventory structure') + for field in ('group', 'trigger', 'timing', 'palette', 'artwork', 'sound', 'input'): + require(transition[field].strip(), f"{transition['id']}: empty {field}") + if transition['status'] == 'partial': + require(transition['gaps'], f"{transition['id']}: partial without a tracked gap") + ui = set(re.findall(r'\bUI_[A-Z_]+\b', (ROOT / 'src/engine/WL_MAIN.h').read_text())) + require(set(data['native_ui']) == ui, f"UI coverage differs: {set(data['native_ui']) ^ ui}") + exits_text = (ROOT / 'WOLFSRC/WL_DEF.H').read_text(encoding='latin1') + exit_enum = re.search(r'typedef\s+enum\s*\{\s*(ex_stillplaying[\s\S]*?)\}\s*exit_t', exits_text) + require(exit_enum, 'Cannot locate DOS exit_t') + exits = set(re.findall(r'\bex_\w+\b', exit_enum[1])) + require(set(data['dos_exits']) == exits, f"DOS exit coverage differs: {set(data['dos_exits']) ^ exits}") + for mapping in (data['native_ui'], data['dos_exits']): + for entry in mapping.values(): + require(entry['transitions'] or entry['classification'] == 'declaration-only', 'Unmapped active state') + require(entry['classification'] and entry['note'], 'Invalid inventory structure') + require(set(entry['transitions']) <= set(ids), 'Invalid inventory structure') + for gap in gaps.values(): + require(gap['priority'] and gap['finding'] and gap['close_with'], 'Invalid inventory structure') + require(set(gap['refs']) <= refs.keys(), 'Invalid inventory structure') + edges = {t['id']: t for t in data['transitions']} + for journey in data['journeys'].values(): + require(journey, 'Empty journey') + previous = None + for step in journey: + edge = edges[step] + require(previous is None or previous == edge['from'], f'Disconnected journey at {step}') + previous = edge['to'] + used_states = {t[k] for t in data['transitions'] for k in ('from', 'to')} + require(used_states == states, f'Unmapped phases: {states - used_states}') + + +def render(data): + def links(names): + return '; '.join(reference(data['references'][name]) for name in names) or 'No DOS-equivalent implementation.' + + lines = ['# DOS interaction and state-transition inventory', '', *data['introduction'], '', + '## How to read the evidence', ''] + for name, meaning in data['statuses'].items(): + lines.append(f'- **{name}**: {meaning}') + lines += ['', f"Inventory: **{len(data['states'])} phases, {len(data['transitions'])} directed transition records**, " + f"all **{len(data['native_ui'])} native UI states** and **{len(data['dos_exits'])} DOS exit values** accounted for.", '', + 'A linked test is evidence only for its stated assertions. It does not prove the complete transition, ' + 'DOS fade/audio equivalence, or a continuous playthrough. This audit adds no new runtime pass claims.', '', + '## Principal journeys', '', '```mermaid', 'flowchart LR', + ' Menu --> Episode --> Difficulty --> Setup --> Psyched --> Reveal --> Gameplay', + ' Gameplay --> DeathTurn --> RedFizzle --> DeathAck', + ' DeathAck --> Restart --> Reveal', + ' DeathAck --> Scores --> Title', + ' Gameplay --> Completion --> Psyched', + ' Gameplay --> SecretCompletion --> Psyched', + ' Gameplay --> BJOrBossReplay --> Victory --> Article --> Scores', + ' Menu --> OrdinaryLoad --> Setup', + ' Gameplay --> QuickLoad --> Gameplay', + ' Menu --> QuitConfirm --> Exit', + '```', '', + 'The graph describes DOS routes. In particular, death restart bypasses Get Psyched, ' + 'and established-slot quickload returns to the existing play loop. Differences below remain open.', ''] + by_id = {t['id']: t for t in data['transitions']} + for name, route in data['journeys'].items(): + description = ' → '.join([by_id[route[0]]['from']] + [by_id[step]['to'] for step in route]) + lines.append(f'- **{name}**: {description}. Rows: {", ".join(route)}.') + lines += ['', '## Findings that prevent a DOS-equivalence claim', ''] + for name, gap in data['gaps'].items(): + affected = ', '.join(t['id'] for t in data['transitions'] if name in t['gaps']) + lines += [f"### {name} — {gap['priority']}: {gap['title']}", '', gap['finding'], '', + f"Source/implementation: {links(gap['refs'])}", '', f'Rows: {affected}.', '', + f"Close with: {gap['close_with']}", ''] + lines += ['## Transition records', ''] + group = None + for t in data['transitions']: + if t['group'] != group: + group = t['group'] + lines += [f'### {group}', ''] + ev = ', '.join(f'[{name}](#{name.lower()})' for name in t['evidence']) or '**No direct executed regression**' + lines += [f"#### {t['id']}: {t['from']} → {t['to']}", '', + f"**Trigger:** {t['trigger']} **Status:** `{t['status']}`.", '', + f"- **DOS source:** {links(t['source'])}", + f"- **Timing:** {t['timing']}", + f"- **Palette:** {t['palette']}", + f"- **Artwork/layout:** {t['artwork']}", + f"- **Sound/music:** {t['sound']}", + f"- **Input/state:** {t['input']}", + f"- **Revive:** {links(t['implementation'])}", + f"- **Regression evidence:** {ev}. Open findings: {', '.join(t['gaps']) or 'none recorded for this row; evidence limits still apply'}.", ''] + lines += ['## Evidence register', ''] + for name, ev in data['evidence'].items(): + lines += [f'### {name}', '', f"**Scope:** {ev['scope']}", '', + '; '.join(reference(ref) for ref in ev['refs']), '', + f"**Observed:** {ev['observation']}", '', f"**Does not establish:** {ev['limits']}", ''] + for label, mapping in [('Native UI coverage', data['native_ui']), ('DOS playstate coverage', data['dos_exits'])]: + lines += [f'## {label}', '', '| State | Classification | Rows | Boundary |', '| --- | --- | --- | --- |'] + for name, entry in mapping.items(): + lines.append(f"| `{name}` | {entry['classification']} | {', '.join(entry['transitions']) or 'declaration only'} | {entry['note']} |") + lines.append('') + lines += ['## Excluded editions, hardware and native adaptations', '', *data['boundaries'], '', + '## Keeping this inventory current', '', + 'The JSON manifest is authoritative for this document. After reviewing changed source/behaviour, ' + 'update the records and evidence, then run:', '', '```sh', + 'python3 scripts/audit_transitions.py --write', 'python3 scripts/audit_transitions.py --check', '```', '', + 'The check rejects missing fields, stale source hashes/anchors, unknown evidence/gaps, disconnected ' + 'journeys, unclassified native UI states, and unclassified DOS exit values. It also checks that this ' + 'document matches the manifest. It does **not** execute the game, discover arbitrary new branch ' + 'conditions, or prove that a cited test asserts every property in its row.', '', + 'For a behaviour change, add an edge-specific regression before changing its evidence status. ' + 'Record the initial/intermediate/final framebuffer, palette, time, sound events, input release/ack, ' + 'map/lives/save/RNG and SDL window/logical geometry where applicable. A successful endpoint or ' + 'a helper that drains loading is insufficient evidence for the presentation between endpoints.', ''] + return '\n'.join(lines) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + group = parser.add_mutually_exclusive_group() + group.add_argument('--write', action='store_true') + group.add_argument('--check', action='store_true') + args = parser.parse_args() + try: + data = json.loads(MANIFEST.read_text(encoding='utf-8')) + validate(data) + expected = render(data) + if args.write: + DOCUMENT.write_text(expected, encoding='utf-8') + else: + require(DOCUMENT.read_text(encoding='utf-8') == expected, 'Document stale; run --write after review') + except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: + parser.exit(1, f'Audit failed: {error}\n') + print(f"Validated {len(data['transitions'])} transitions, {len(data['states'])} phases, " + f"{len(data['native_ui'])} UI states, {len(data['dos_exits'])} DOS exits; " + f"{len(data['gaps'])} findings remain open. No runtime behaviour was certified by this check.") + + +if __name__ == '__main__': + main() diff --git a/scripts/compare_demo_traces.py b/scripts/compare_demo_traces.py new file mode 100644 index 00000000..2ca4ea15 --- /dev/null +++ b/scripts/compare_demo_traces.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Compare private traces or derive asset-free per-frame DOS regression hashes.""" +# SPDX-License-Identifier: GPL-2.0-only +import argparse +import hashlib +import json +from pathlib import Path +import sys +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +from demo_trace_tools import compare, digest, dos_frames, native_frames +from demo_reference import ASSETS, EXE_SHA, MAP_SHA + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--dos', required=True, type=Path) + parser.add_argument('--native', type=Path) + parser.add_argument('--write-golden', type=Path) + parser.add_argument('--data', type=Path) + args = parser.parse_args() + reference = lambda: dos_frames(args.dos, ROOT / 'WOLFSRC/WOLF3D.MAP') + if args.native: + difference = compare(native_frames(args.native), reference()) + if difference: + print(json.dumps(difference)) + return 1 + print('All native/DOS frame fields match.') + if args.write_golden: + if args.data is None: + parser.error('--write-golden requires --data for source identities') + hashes = [[] for _ in range(4)] + for frame in reference(): + number, command = frame['F'][:2] + if command != len(hashes[number])+1: + raise ValueError('Reference command gap') + hashes[number].append(digest(frame)) + if list(map(len, hashes)) != [691,1899,1140,1656]: + raise ValueError('Reference did not complete all four recordings') + identities = {} + for name in ASSETS: + source = next(p for p in args.data.iterdir() if p.name.upper() == name+'.WL6') + identities[name+'.WL6'] = hashlib.sha256(source.read_bytes()).hexdigest() + result = {'schema': 1, 'reference_exe': EXE_SHA, 'reference_map': MAP_SHA, + 'view_size': 15, 'sound': 'off', 'assets': identities, 'frames': hashes} + args.write_golden.write_text(json.dumps(result, indent=2)+'\n') + print('Wrote DOS frame hashes; no commands, maps or PCM assets included.') + return 0 + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/scripts/demo_reference.py b/scripts/demo_reference.py new file mode 100644 index 00000000..9795f865 --- /dev/null +++ b/scripts/demo_reference.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Build a private instrumented original DOS EXE; never edit WOLFSRC or assets. + +GNU binutils assemble the logger. The historical Borland executable and its MAP +are the reference, not a native recompilation or the port's simulation. Only +attract-menu selection, acknowledgement and diagnostic I/O are instrumented. +""" +# SPDX-License-Identifier: GPL-2.0-only +import argparse +import hashlib +from pathlib import Path +import shutil +import struct +import subprocess + +ROOT = Path(__file__).resolve().parents[1] +EXE_SHA = '8614a3e4623b66181bf0aa88fc5a4ca36cb97fe5ef8c3b903954dfaaf683ab9b' +MAP_SHA = 'b3058257601f156fee914dcc926b5857753326ac0f1eada65bb0856a7b3f1928' +ASSETS = ('AUDIOHED', 'AUDIOT', 'GAMEMAPS', 'MAPHEAD', 'VGADICT', 'VGAGRAPH', 'VGAHEAD', 'VSWAP') + +def build(directory, data, fast=False): + directory = Path(directory).resolve() + if directory.is_relative_to(ROOT) and not directory.is_relative_to(ROOT / 'build'): + raise ValueError('Use an ignored build directory or an external private directory') + if directory == Path(data).resolve(): + raise ValueError('Output must be separate from original data') + # Diagnostics and original data must remain private, outside tracked source. + if directory.exists() and any(directory.iterdir()): + raise ValueError('Reference output directory must be new or empty') + directory.mkdir(parents=True, exist_ok=True) + binary = bytearray((ROOT / 'WOLFSRC/WOLF3D.EXE').read_bytes()) + symbols = (ROOT / 'WOLFSRC/WOLF3D.MAP').read_bytes() + if hashlib.sha256(binary).hexdigest() != EXE_SHA or hashlib.sha256(symbols).hexdigest() != MAP_SHA: + raise ValueError('Unrecognised original executable/map: refusing address-based instrumentation') + subprocess.run(['as', '--32', str(ROOT / 'scripts/demo_reference.s'), '-o', str(directory / 'logger.o')], check=True) + subprocess.run(['ld', '-m', 'elf_i386', '-Ttext=0x15aa', '--oformat', 'binary', str(directory / 'logger.o'), '-o', str(directory / 'logger.bin')], check=True) + labels = {line.split()[2]: int(line.split()[0],16) for line in + subprocess.check_output(['nm','-n',str(directory/'logger.o')],text=True).splitlines() + if len(line.split()) == 3} + header = struct.unpack_from(' 0x6070-0x5e9a: + raise ValueError('Logger exceeds replaced DemoLoop code region') + image[0x5e9a:0x5e9a+len(stub)] = stub + relocations = [(o, s) for o, s in relocations if not 0x5e9a <= s*16+o < 0x5e9a+len(stub)] + # IN_Ack is only used for startup/menus in this private demo runner. + image[0x18262] = 0xcb + if fast: + # Skip the wall-clock wait, retaining the original TimeCount update and + # tics=DEMOTICS. Sound is disabled. Never used in the native runtime. + image[0xd385:0xd3a0] = bytes([0x90])*27 + for address, opcode, offset in ((0x5e8a, 0xea, 0x15aa), (0xe032, 0x9a, 0x15aa+labels['frame'])): + image[address:address+5] = struct.pack(' header: + raise ValueError('MZ relocation table has no room') + for i, entry in enumerate(relocations): + struct.pack_into(' len(data): + raise ValueError('Truncated OMF record header') + kind, length = data[position], int.from_bytes(data[position+1:position+3], 'little') + end = position + 3 + length + if length < 1 or end > len(data): + raise ValueError('Truncated OMF record') + record = data[position:end] + # Zero denotes an omitted OMF checksum (used by this file's headers). + if record[-1] and sum(record) % 256: + raise ValueError('Invalid OMF checksum') + payload = record[3:-1] + if kind == 0xa0: + if len(payload) < 3 or payload[0] != 1: + raise ValueError('Unsupported sign-on OMF segment') + offset = int.from_bytes(payload[1:3], 'little') + content = payload[3:] + if offset + len(content) > PIXELS or any(covered[offset:offset+len(content)]): + raise ValueError('Overlapping or oversized OMF pixels') + pixels[offset:offset+len(content)] = content + covered[offset:offset+len(content)] = bytes([1])*len(content) + elif kind not in (0x80, 0x88, 0x96, 0x98, 0x90, 0x8a): + raise ValueError('Unsupported OMF record in sign-on object') + position = end + if not all(covered): + raise ValueError('Incomplete OMF sign-on pixels') + return bytes(pixels) + + +def read_source(source): + with source.open('rb') as stream: + data = stream.read(1024 * 1024 + 1) + if len(data) > 1024 * 1024: + raise ValueError('DOS executable/object exceeds supported size') + return data + + +def select_source(source): + """Accept an asset file, Steam install/base, repository or WOLFSRC directory.""" + if not source.is_dir(): + return source + for relative in ('wolf3d.exe', 'base/wolf3d.exe', 'OBJ/SIGNON.OBJ', + 'WOLFSRC/OBJ/SIGNON.OBJ', 'SIGNON.OBJ'): + candidate = source + for name in relative.split('/'): + matches = [p for p in candidate.iterdir() if p.name.lower() == name.lower()] if candidate.is_dir() else [] + if len(matches) != 1: + candidate = None + break + candidate = matches[0] + if candidate and candidate.is_file(): + digest = hashlib.sha256(read_source(candidate)).hexdigest() + if digest in (EXE_SHA256, OBJECT_SHA256): + return candidate + raise ValueError('No supported wolf3d.exe or source SIGNON.OBJ found in directory') + + +def decode_stream(data, offset, limit): + """Decode the LZEXE literal/backreference stream with strict input bounds.""" + position = offset + + def byte(): + nonlocal position + if not 0 <= position < len(data): + raise ValueError('Truncated LZEXE stream') + value = data[position] + position += 1 + return value + + def word(): + return byte() | (byte() << 8) + + control, remaining = word(), 16 + + def bit(): + nonlocal control, remaining + result = control & 1 + remaining -= 1 + # LZEXE prefetches the next control word before consuming token bytes. + if remaining == 0: + control, remaining = word(), 16 + else: + control >>= 1 + return result + + output = bytearray() + while True: + if bit(): + if len(output) >= limit: + raise ValueError('LZEXE output exceeds expected size') + output.append(byte()) + continue + if bit(): + low, high = byte(), byte() + distance = (low | ((high & 0xf8) << 5) | 0xe000) - 0x10000 + length = (high & 7) + 2 + if length == 2: + length = byte() + if length == 0: + return bytes(output) + if length == 1: # Segment adjustment; no output bytes. + continue + length += 1 + else: + length = ((bit() << 1) | bit()) + 2 + distance = byte() - 256 + if len(output) + length > limit: + raise ValueError('LZEXE output exceeds expected size') + if len(output) + distance < 0: + raise ValueError('Invalid LZEXE backreference') + for _ in range(length): # Backreferences can overlap their destination. + output.append(output[len(output) + distance]) + + +def extract(data): + digest = hashlib.sha256(data).hexdigest() + if digest == OBJECT_SHA256: + pixels = decode_object(data) + if hashlib.sha256(pixels).hexdigest() != SOURCE_SIGNON_SHA256: + raise ValueError('Source sign-on pixel checksum mismatch') + return pixels + if digest != EXE_SHA256: + raise ValueError('Unsupported DOS EXE/object revision (SHA-256 mismatch); see docs/MILESTONE11_SIGNON.md') + if len(data) < 32 or data[:2] != b'MZ' or data[28:32] != b'LZ91': + raise ValueError('Expected verified LZEXE 0.91 executable') + header = struct.unpack_from('<16H', data) + stub = (header[4] + header[11]) * 16 + if stub + 16 > len(data): + raise ValueError('Invalid LZEXE information offset') + info = struct.unpack_from('<8H', data, stub) + start = (header[11] - info[4] + header[4]) * 16 + image = decode_stream(data, start, LOAD_SIZE) + if len(image) != LOAD_SIZE or hashlib.sha256(image).hexdigest() != LOAD_SHA256: + raise ValueError('Decompressed load-image checksum mismatch') + pixels = image[SIGNON_OFFSET:SIGNON_OFFSET + PIXELS] + if len(pixels) != PIXELS or hashlib.sha256(pixels).hexdigest() != SIGNON_SHA256: + raise ValueError('Sign-on pixel checksum mismatch') + return pixels + + +def export(source, destination): + source, destination = select_source(Path(source).resolve()), Path(destination).resolve() + if destination == source: + raise ValueError('Output must be separate from the original executable') + if destination.is_relative_to(ROOT) and not any(destination.is_relative_to(ROOT / name) + for name in ('build', 'data', 'game-data')): + raise ValueError('Write commercial artwork outside the repository or under ignored build/data/game-data') + pixels = extract(read_source(source)) + with destination.open('xb') as stream: # Never replace an existing file. + stream.write(pixels) + return hashlib.sha256(pixels).hexdigest() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('source', type=Path, help='Verified wolf3d.exe, SIGNON.OBJ, Steam directory or Wolf source directory') + parser.add_argument('output', type=Path, help='New private SIGNON.RAW, exactly 64000 row-major bytes') + args = parser.parse_args() + try: + checksum = export(args.source, args.output) + except (OSError, ValueError) as error: + parser.exit(1, f'Sign-on extraction failed: {error}\n') + print(f'Extracted 320x200 indexed DOS sign-on: {args.output}\nSHA-256: {checksum}') + + +if __name__ == '__main__': + main() diff --git a/scripts/ui_reference.py b/scripts/ui_reference.py new file mode 100644 index 00000000..939193c3 --- /dev/null +++ b/scripts/ui_reference.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Private original-DOS UI/progress pixel oracle; no commercial assets emitted to Git.""" +# SPDX-License-Identifier: GPL-2.0-only +import hashlib +from pathlib import Path +import shutil +import struct +import subprocess +from demo_reference import ROOT, EXE_SHA, MAP_SHA, ASSETS + + +def build(directory, data): + directory, data = Path(directory).resolve(), Path(data).resolve() + if directory == data or (directory.is_relative_to(ROOT) and not directory.is_relative_to(ROOT/'build')): + raise ValueError('Use a separate private output directory') + if directory.exists() and any(directory.iterdir()): + raise ValueError('Output directory must be new or empty') + original = (ROOT/'WOLFSRC/WOLF3D.EXE').read_bytes() + symbols = (ROOT/'WOLFSRC/WOLF3D.MAP').read_bytes() + if hashlib.sha256(original).hexdigest()!=EXE_SHA or hashlib.sha256(symbols).hexdigest()!=MAP_SHA: + raise ValueError('Unknown historical EXE/MAP; refusing instrumentation') + directory.mkdir(parents=True,exist_ok=True) + subprocess.run(['as','--32',str(ROOT/'scripts/ui_reference.s'),'-o',str(directory/'ui.o')],check=True) + subprocess.run(['ld','-m','elf_i386','-Ttext=0x15aa','--oformat','binary',str(directory/'ui.o'),'-o',str(directory/'ui.bin')],check=True) + labels={line.split()[2]:int(line.split()[0],16) for line in subprocess.check_output(['nm','-n',str(directory/'ui.o')],text=True).splitlines() if len(line.split())==3} + stub=(directory/'ui.bin').read_bytes() + if len(stub)>0x6070-0x5e9a: + raise ValueError('Oracle exceeds unused DemoLoop region') + binary=bytearray(original) + header=struct.unpack_from('header: + raise ValueError('Relocation table capacity exceeded') + for i,entry in enumerate(relocations):struct.pack_into(' +#include +#include + +#define CA_MAX_FILE ((size_t)32 * 1024 * 1024) +#define CA_MAX_CHUNK ((size_t)4 * 1024 * 1024) +#define SPARSE UINT32_C(0xffffff) + +memptr grsegs[NUMCHUNKS]; +size_t grsizes[NUMCHUNKS]; +pictabletype pictable[NUMPICS]; +static huffnode grhuffman[255]; +static uint32_t grstarts[NUMCHUNKS + 1]; +static FILE *grhandle; +static char error[512], data_directory[4096]; +const char *CA_DataDirectory(void) { return data_directory; } + +const char *CA_Error(void) { return error; } +bool CA_Fail(const char *format, ...) +{ + va_list args; + va_start(args, format); + (void)vsnprintf(error, sizeof(error), format, args); + va_end(args); + return false; +} +static uint16_t ReadLE16(const w3r_byte *p) +{ + return (uint16_t)((uint16_t)p[0] | (uint16_t)((uint16_t)p[1] << 8)); +} +static uint32_t ReadLE32(const w3r_byte *p) +{ + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | + ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} + +static bool ValidateNode(const huffnode table[255], unsigned node, w3r_byte state[255]) +{ + uint16_t children[2]; + if (state[node] == 1) return CA_Fail("Cyclic graphics Huffman dictionary"); + if (state[node] == 2) return true; + state[node] = 1; + children[0] = table[node].bit0; + children[1] = table[node].bit1; + for (unsigned i = 0; i < 2; ++i) { + if (children[i] > 510) return CA_Fail("Invalid graphics Huffman node %u", (unsigned)children[i]); + if (children[i] >= 256 && !ValidateNode(table, (unsigned)children[i] - 256, state)) + return false; + } + state[node] = 2; + return true; +} + +bool CAL_ValidateHuffman(const huffnode table[255]) +{ + w3r_byte state[255] = {0}; + if (!table) return CA_Fail("Missing Huffman dictionary"); + for (unsigned i = 0; i < 255; ++i) + if (!ValidateNode(table, i, state)) return false; + return true; +} + +bool CAL_HuffExpand(const w3r_byte *source, size_t source_length, + w3r_byte *dest, size_t length, const huffnode table[255]) +{ + size_t input = 0, output = 0; + unsigned mask = 1, node = 254, depth = 0; + if ((!source && source_length) || (!dest && length) || !table) + return CA_Fail("Invalid Huffman buffers"); + while (output < length) { + uint16_t code; + if (input >= source_length) return CA_Fail("Truncated graphics Huffman stream"); + code = (source[input] & mask) ? table[node].bit1 : table[node].bit0; + mask <<= 1; + if (mask == 256) { mask = 1; ++input; } + if (code < 256) { + dest[output++] = (w3r_byte)code; + node = 254; + depth = 0; + } else { + if (code > 510 || ++depth > 255) return CA_Fail("Invalid/cyclic graphics Huffman code"); + node = (unsigned)code - 256; + } + } + return true; +} + +static FILE *CA_Open(const char *directory, const char *name) +{ + FILE *file = CA_OpenDataFile(directory, name); + if (!file) (void)CA_Fail("Cannot open %s in '%s' (missing, ambiguous or unreadable; use --data)", name, directory); + return file; +} + +static bool CA_FileSize(FILE *file, const char *name, size_t *size) +{ + long end; + if (fseek(file, 0, SEEK_END) != 0 || (end = ftell(file)) <= 0 || + (unsigned long)end > CA_MAX_FILE || fseek(file, 0, SEEK_SET) != 0) + return CA_Fail("%s is empty, unreadable or larger than 32 MiB", name); + *size = (size_t)end; + return true; +} + +static bool CA_Read(FILE *file, void *dest, size_t length) +{ + return fread(dest, 1, length, file) == length || CA_Fail("Truncated/unreadable game-data file"); +} + +void CA_Shutdown(void) +{ + CA_UncacheMap(); PM_Shutdown(); data_directory[0]=0; + if (grhandle) { (void)fclose(grhandle); grhandle = NULL; } + for (int i = 0; i < NUMCHUNKS; ++i) { + if (grsegs[i]) (void)MM_FreePtr(&grsegs[i]); + grsizes[i] = 0; + } + memset(pictable, 0, sizeof(pictable)); +} + +static bool CAL_SetupGrFile(const char *directory) +{ + w3r_byte dict[1024], head[(NUMCHUNKS + 1) * 3]; + FILE *file; + size_t size; + file = CA_Open(directory, "VGADICT.WL6"); + if (!file) return false; + bool ok = CA_FileSize(file, "VGADICT.WL6", &size); + if (ok && size != 1020 && size != 1024) ok = CA_Fail("VGADICT.WL6 must contain 255 or 256 four-byte nodes"); + if (ok) ok = CA_Read(file, dict, size); + (void)fclose(file); + if (!ok) return false; + for (size_t i = 0; i < 255; ++i) { + grhuffman[i].bit0 = ReadLE16(dict + i * 4); + grhuffman[i].bit1 = ReadLE16(dict + i * 4 + 2); + } + if (!CAL_ValidateHuffman(grhuffman)) return false; + file = CA_Open(directory, "VGAHEAD.WL6"); + if (!file) return false; + ok = CA_FileSize(file, "VGAHEAD.WL6", &size); + if (ok && size != sizeof(head)) ok = CA_Fail("Unsupported WL6 graphics layout: expected 149 chunks (450-byte VGAHEAD)"); + if (ok) ok = CA_Read(file, head, sizeof(head)); + (void)fclose(file); + if (!ok) return false; + grhandle = CA_Open(directory, "VGAGRAPH.WL6"); + if (!grhandle || !CA_FileSize(grhandle, "VGAGRAPH.WL6", &size)) return false; + uint32_t previous = 0; + for (size_t i = 0; i <= NUMCHUNKS; ++i) { + uint32_t offset = (uint32_t)head[i * 3] | ((uint32_t)head[i * 3 + 1] << 8) | + ((uint32_t)head[i * 3 + 2] << 16); + grstarts[i] = offset; + if (offset == SPARSE) continue; + if (offset < previous || offset > size) return CA_Fail("Invalid/nonmonotonic VGAHEAD offset at chunk %zu", i); + previous = offset; + } + if (grstarts[0] != 0 || grstarts[NUMCHUNKS] != size) + return CA_Fail("VGAHEAD terminal offset does not match VGAGRAPH size"); + if (!CA_CacheGrChunk(STRUCTPIC)) return false; + if (grsizes[STRUCTPIC] != NUMPICS * 4) return CA_Fail("Unsupported WL6 picture table size"); + const w3r_byte *raw = grsegs[STRUCTPIC]; + for (size_t i = 0; i < NUMPICS; ++i) { + pictable[i].width = ReadLE16(raw + i * 4); + pictable[i].height = ReadLE16(raw + i * 4 + 2); + } + return true; +} + +bool CA_Startup(const char *data_dir) +{ + static const char *required[] = {"VSWAP.WL6", "GAMEMAPS.WL6", "MAPHEAD.WL6", "AUDIOT.WL6", "AUDIOHED.WL6"}; + CA_Shutdown(); + error[0] = '\0'; + if (!data_dir || !*data_dir) return CA_Fail("Empty data directory; supply --data /path/to/WL6"); + if (strlen(data_dir)>=sizeof(data_directory)) return CA_Fail("Data directory too long"); + /* Graphics startup checks presence; level and audio parsers have separate lifecycles. */ + for (size_t i = 0; i < sizeof(required) / sizeof(required[0]); ++i) { + size_t size; + w3r_byte probe; + FILE *file = CA_Open(data_dir, required[i]); + if (!file) return false; + bool ok = CA_FileSize(file, required[i], &size) && CA_Read(file, &probe, 1); + (void)fclose(file); + if (!ok) return false; + } + if (!CAL_SetupGrFile(data_dir)) { CA_Shutdown(); return false; } + strcpy(data_directory,data_dir); + return true; +} + +bool CA_GrChunkPresent(int chunk) +{ return grhandle && chunk>=0 && chunk= NUMCHUNKS) + return CA_Fail("Invalid graphics cache request %d", chunk); + if (grsegs[chunk]) { (void)MM_SetPurge(&grsegs[chunk], 0); return true; } + if (grstarts[chunk] == SPARSE) return CA_Fail("Missing/sparse graphics chunk %d", chunk); + next = chunk + 1; + while (next <= NUMCHUNKS && grstarts[next] == SPARSE) ++next; + if (next > NUMCHUNKS) return CA_Fail("Missing graphics chunk end offset"); + length = (size_t)(grstarts[next] - grstarts[chunk]); + if (length < 5 || length > CA_MAX_CHUNK) return CA_Fail("Invalid compressed graphics chunk size"); + if (!MM_GetPtr(&compressed, length)) return CA_Fail("Out of memory reading graphics chunk"); + ok = fseek(grhandle, (long)grstarts[chunk], SEEK_SET) == 0 && CA_Read(grhandle, compressed, length); + if (!ok) { (void)CA_Fail("Cannot read graphics chunk %d", chunk); goto done; } + const w3r_byte *source = compressed; + /* Original tile chunks omit the four-byte size field. */ + if (chunk >= STARTTILE8 && chunk < STARTEXTERNS) { + expanded = NUMTILE8 * 64; + } else { + expanded = ReadLE32(source); + source += 4; + length -= 4; + } + if (!expanded || expanded > CA_MAX_CHUNK) { ok = CA_Fail("Invalid expanded graphics chunk size"); goto done; } + if (!MM_GetPtr(&grsegs[chunk], expanded)) { ok = CA_Fail("Out of memory caching graphics chunk"); goto done; } + ok = CAL_HuffExpand(source, length, grsegs[chunk], expanded, grhuffman); + if (!ok) (void)MM_FreePtr(&grsegs[chunk]); + else grsizes[chunk] = expanded; +done: + (void)MM_FreePtr(&compressed); + return ok; +} + +bool CA_CacheScreen(int chunk) +{ + if (chunk < STARTPICS || chunk >= STARTPICS + NUMPICS) + return CA_Fail("Invalid full-screen picture %d", chunk); + if (pictable[chunk - STARTPICS].width != W3R_SCREEN_WIDTH || + pictable[chunk - STARTPICS].height != W3R_SCREEN_HEIGHT) + return CA_Fail("Picture %d is not a 320x200 screen", chunk); + if (!CA_CacheGrChunk(chunk)) return false; + if (!VL_MemToScreen(grsegs[chunk], grsizes[chunk], W3R_SCREEN_WIDTH, W3R_SCREEN_HEIGHT, 0, 0)) + return CA_Fail("Invalid full-screen graphics chunk length"); + return true; +} diff --git a/src/engine/ID_CA.h b/src/engine/ID_CA.h new file mode 100644 index 00000000..fe8f6fec --- /dev/null +++ b/src/engine/ID_CA.h @@ -0,0 +1,27 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef ID_CA_H +#define ID_CA_H +#include "ID_MM.h" +#include "w3r_types.h" +#include "GFXV_WL6.h" +#include +#include + +typedef struct { w3r_word bit0, bit1; } huffnode; +typedef struct { w3r_word width, height; } pictabletype; +extern memptr grsegs[NUMCHUNKS]; +extern size_t grsizes[NUMCHUNKS]; +extern pictabletype pictable[NUMPICS]; + +bool CAL_ValidateHuffman(const huffnode table[255]); +/* Same root/LSB-first codes as the original asm, now with source bounds. */ +bool CAL_HuffExpand(const w3r_byte *source, size_t source_length, + w3r_byte *dest, size_t length, const huffnode table[255]); +bool CA_Startup(const char *data_dir); +void CA_Shutdown(void); +bool CA_CacheGrChunk(int chunk); +bool CA_GrChunkPresent(int chunk); +bool CA_CacheScreen(int chunk); +const char *CA_Error(void); +bool CA_Fail(const char *format, ...); +#endif diff --git a/src/engine/ID_FILE.c b/src/engine/ID_FILE.c new file mode 100644 index 00000000..2368b783 --- /dev/null +++ b/src/engine/ID_FILE.c @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Portable bounded form of CA_ReadFile/CA_FarRead for original archives. */ +#include "ID_FILE.h" +#include "ID_CA.h" +#include "platform/data_file.h" +#include +bool CA_ReadDataFile(const char *name, memptr *data, size_t *size) +{ + if (!name || !data || !size || *data) return CA_Fail("Invalid archive read request"); + if (!*CA_DataDirectory()) return CA_Fail("Configure a data directory before reading archives"); + FILE *file = CA_OpenDataFile(CA_DataDirectory(),name); + long length; + if (!file) return CA_Fail("Cannot open %s",name); + bool ok = fseek(file,0,SEEK_END)==0 && (length=ftell(file))>0 && length<=32*1024*1024 && fseek(file,0,SEEK_SET)==0; + if (!ok) { (void)fclose(file); return CA_Fail("Invalid %s file size",name); } + *size=(size_t)length; + ok=MM_GetPtr(data,*size); + if (ok) ok=fread(*data,1,*size,file)==*size; + (void)fclose(file); + if (!ok) { if (*data) (void)MM_FreePtr(data); return CA_Fail("Cannot read %s",name); } + return true; +} diff --git a/src/engine/ID_FILE.h b/src/engine/ID_FILE.h new file mode 100644 index 00000000..15f332d3 --- /dev/null +++ b/src/engine/ID_FILE.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef ID_FILE_H +#define ID_FILE_H +#include "ID_MM.h" +#include +static inline uint16_t CA_LE16(const unsigned char *p) { return (uint16_t)((unsigned)p[0] | ((unsigned)p[1]<<8)); } +static inline uint32_t CA_LE32(const unsigned char *p) { return (uint32_t)p[0] | ((uint32_t)p[1]<<8) | ((uint32_t)p[2]<<16) | ((uint32_t)p[3]<<24); } +bool CA_ReadDataFile(const char *name, memptr *data, size_t *size); +const char *CA_DataDirectory(void); +#endif diff --git a/src/engine/ID_IN.c b/src/engine/ID_IN.c new file mode 100644 index 00000000..a8bcfab8 --- /dev/null +++ b/src/engine/ID_IN.c @@ -0,0 +1,68 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* ID_IN.C keyboard make/break state and ASCII lookup, ported from DOS set-1. */ +#include "ID_IN.h" +#include "WL_CONTROLS.h" +#include +bool Keyboard[128]; +static bool pressed[128],ack,caps; +static char ascii_chars[128]; +void IN_AckEvent(void) { ack=true; } +static unsigned ascii_scans[128], ascii_read, ascii_write; +uint8_t LastScan; +char LastASCII; +char IN_ScanASCII(unsigned scan) +{ + static const char row1[] = "qwertyuiop", row2[] = "asdfghjkl", row3[] = "zxcvbnm"; + if (scan >= 0x10 && scan <= 0x19) return row1[scan - 0x10]; + if (scan >= 0x1e && scan <= 0x26) return row2[scan - 0x1e]; + if (scan >= 0x2c && scan <= 0x32) return row3[scan - 0x2c]; + if (scan >= 2 && scan <= 10) return (char)('1' + scan - 2); + if (scan == 11) return '0'; + switch(scan) { + case 0x0c:return '-';case 0x0d:return '=';case 0x1a:return '[';case 0x1b:return ']'; + case 0x27:return ';';case 0x28:return '\'';case 0x29:return '`';case 0x2b:return '\\'; + case 0x33:return ',';case 0x34:return '.';case 0x35:return '/';default:break; + } + if (scan == sc_Space) return ' '; + return 0; +} +void IN_ClearPressed(void) { ack=false; memset(pressed, 0, sizeof(pressed)); LastScan = 0; LastASCII = 0; ascii_read = ascii_write = 0;CT_EndTic(); } +void IN_ClearKeysDown(void) { memset(Keyboard, 0, sizeof(Keyboard)); IN_ClearPressed();CT_Clear(); } +void IN_KeyEvent(unsigned scan,bool down) { CT_LegacyKey(scan,down);IN_MenuKeyEvent(scan,down); } +void IN_MenuKeyEvent(unsigned scan, bool down) +{ + if (!scan || scan >= 128) return; + if (down && !Keyboard[scan]) { if(scan==0x3a) caps=!caps;pressed[scan] = true; LastScan = (uint8_t)scan; char ascii = IN_ScanASCII(scan); if (ascii) { + LastASCII = ascii; + unsigned next = (ascii_write+1)%128; + if (next == ascii_read) ascii_read = (ascii_read+1)%128; + bool shift=Keyboard[0x2a] || Keyboard[0x36]; + if(ascii>='a' && ascii<='z') { if(shift!=caps) ascii=(char)(ascii-'a'+'A'); } + else if(shift) { + const char *plain="1234567890-=[];'`\\,./",*shifted="!@#$%^&*()_+{}:\"~|<>?"; + const char *p=strchr(plain,ascii);if(p) ascii=shifted[p-plain]; + } + ascii_scans[ascii_write] = scan;ascii_chars[ascii_write]=ascii;ascii_write = next; + } } + Keyboard[scan] = down; +} +bool IN_ConsumePress(unsigned scan) +{ + if (scan >= 128) return false; + bool result = pressed[scan]; pressed[scan] = false; return result; +} +bool IN_AnyPressed(void) +{ + if(ack) return true; + for (unsigned i = 1; i < 128; ++i) if (pressed[i]) return true; + return false; +} + +char IN_NextASCII(void) +{ + if (ascii_read == ascii_write) return 0; + unsigned scan = ascii_scans[ascii_read];char ascii=ascii_chars[ascii_read];ascii_read = (ascii_read+1)%128; + if (ascii != ' ') pressed[scan] = false; + return ascii; +} +bool IN_PressPending(unsigned scan) { return scan<128 && pressed[scan]; } diff --git a/src/engine/ID_IN.h b/src/engine/ID_IN.h new file mode 100644 index 00000000..b459b428 --- /dev/null +++ b/src/engine/ID_IN.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Set-1 keyboard state from WOLFSRC/ID_IN.H/C, without DOS IRQ handling. */ +#ifndef ID_IN_H +#define ID_IN_H +#include +#include +enum { sc_None = 0, sc_Escape = 1, sc_Enter = 0x1c, sc_Space = 0x39, + sc_UpArrow = 0x48, sc_DownArrow = 0x50, sc_LeftArrow = 0x4b, sc_RightArrow = 0x4d, + sc_Pause = 0x7f, sc_Y = 0x15, sc_N = 0x31 }; +extern bool Keyboard[128]; +extern uint8_t LastScan; +extern char LastASCII; +void IN_ClearKeysDown(void); +void IN_ClearPressed(void); +void IN_KeyEvent(unsigned scan, bool down); +void IN_MenuKeyEvent(unsigned scan,bool down); +bool IN_ConsumePress(unsigned scan); +bool IN_AnyPressed(void); +void IN_AckEvent(void); /* Fresh mouse press outside relative gameplay. */ +char IN_ScanASCII(unsigned scan); +char IN_NextASCII(void); +bool IN_PressPending(unsigned scan); +#endif diff --git a/src/engine/ID_MAP.c b/src/engine/ID_MAP.c new file mode 100644 index 00000000..3a64e6db --- /dev/null +++ b/src/engine/ID_MAP.c @@ -0,0 +1,105 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WOLFSRC/ID_CA.C CAL_CarmackExpand, CA_RLEWexpand, CA_CacheMap. + Three disk planes are retained, including the unused third plane. */ +#include "ID_MAP.h" +#include "ID_CA.h" +#include "ID_FILE.h" +#include +static memptr mapmem; +const maptype *CA_Map(void) { return mapmem; } +void CA_UncacheMap(void) { if (mapmem) (void)MM_FreePtr(&mapmem); } +bool CAL_CarmackExpand(const w3r_byte *src,size_t bytes,w3r_word *dst,size_t words) +{ + size_t in=0,out=0; + if ((!src && bytes) || (!dst && words)) return CA_Fail("Invalid Carmack buffers"); + while (out>8,count=ch&255; + if (tag!=0xa7 && tag!=0xa8) { dst[out++]=(w3r_word)ch; continue; } + if (!count) { + if (in>=bytes) return CA_Fail("Truncated escaped Carmack tag"); + dst[out++]=(w3r_word)((ch&0xff00)|src[in++]); continue; + } + size_t offset; + if (tag==0xa7) { + if (in>=bytes) return CA_Fail("Truncated Carmack near offset"); + unsigned back=src[in++]; + if (!back || back>out) return CA_Fail("Invalid Carmack near reference"); + offset=out-back; + } else { + if (bytes-in<2) return CA_Fail("Truncated Carmack far offset"); + offset=CA_LE16(src+in); in+=2; + if (offset>=out) return CA_Fail("Invalid Carmack far reference"); + } + if (count>words-out) return CA_Fail("Carmack output overrun"); + /* Overlap is intentional: original forward LZ word copies. */ + while (count--) dst[out++]=dst[offset++]; + } + return true; +} +bool CA_RLEWexpand(const w3r_word *src,size_t words,w3r_word *dst,size_t output,w3r_word tag) +{ + size_t in=0,out=0; + if ((!src && words) || (!dst && output)) return CA_Fail("Invalid RLEW buffers"); + while (out=words) return CA_Fail("Truncated RLEW stream"); + w3r_word value=src[in++]; + if (value!=tag) { dst[out++]=value; continue; } + if (words-in<2) return CA_Fail("Truncated RLEW run"); + size_t count=src[in++]; value=src[in++]; + if (!count || count>output-out) return CA_Fail("Invalid RLEW run length"); + while (count--) dst[out++]=value; + } + return true; +} +bool CA_ReadMap(unsigned number,maptype *destination) +{ + memptr head=NULL,file=NULL,pending=NULL,scratch=NULL; + size_t heads=0,bytes=0; bool ok=false; + if (!destination || number>=60) return CA_Fail("Unsupported WL6 map number"); + if (!CA_ReadDataFile("MAPHEAD.WL6",&head,&heads) || !CA_ReadDataFile("GAMEMAPS.WL6",&file,&bytes)) goto done; + if (heads<242 || heads>402 || (heads-2)%4) { (void)CA_Fail("Invalid MAPHEAD table"); goto done; } + const w3r_byte *h=head,*raw=file; + uint32_t at=CA_LE32(h+2+number*4); + if (!at || at==UINT32_MAX || at>bytes || bytes-at<38) { (void)CA_Fail("Invalid GAMEMAPS map header offset"); goto done; } + const w3r_byte *mh=raw+at; + if (CA_LE16(mh+18)!=64 || CA_LE16(mh+20)!=64) { (void)CA_Fail("Map not 64x64"); goto done; } + if (!MM_GetPtr(&pending,sizeof(maptype))) { (void)CA_Fail("Map allocation failed"); goto done; } + maptype *map=pending; map->number=number; memcpy(map->name,mh+22,16); map->name[16]=0; + for (unsigned plane=0;plane<3;++plane) { + uint32_t start=CA_LE32(mh+plane*4); size_t length=CA_LE16(mh+12+plane*2); + if (length<4 || start>bytes || length>bytes-start || + (start<(size_t)at+38 && (size_t)start+length>at)) { (void)CA_Fail("Invalid map plane %u bounds",plane); goto done; } + for (unsigned prior=0;priorplanes[plane],MAPAREA,CA_LE16(h))) goto done; + (void)MM_FreePtr(&scratch); + } + memcpy(destination,pending,sizeof(maptype));ok=true; +done: + if (scratch) (void)MM_FreePtr(&scratch); + if (pending) (void)MM_FreePtr(&pending); + if (head) (void)MM_FreePtr(&head); + if (file) (void)MM_FreePtr(&file); + return ok; +} + +bool CA_InstallMap(const maptype *map) +{ + if(!map || map->number>=60) return CA_Fail("Invalid staged map"); + if(!mapmem && !MM_GetPtr(&mapmem,sizeof(maptype))) return CA_Fail("Map allocation failed"); + memcpy(mapmem,map,sizeof(maptype));return true; +} +bool CA_CacheMap(unsigned number) +{ + maptype pending; + return CA_ReadMap(number,&pending) && CA_InstallMap(&pending); +} diff --git a/src/engine/ID_MAP.h b/src/engine/ID_MAP.h new file mode 100644 index 00000000..8b0ad1c8 --- /dev/null +++ b/src/engine/ID_MAP.h @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef ID_MAP_H +#define ID_MAP_H +#include "w3r_types.h" +#include +#include +#define MAPSIZE 64 +#define MAPAREA 4096 +typedef struct { w3r_word planes[3][MAPAREA]; char name[17]; unsigned number; } maptype; +bool CAL_CarmackExpand(const w3r_byte *source,size_t bytes,w3r_word *dest,size_t words); +bool CA_RLEWexpand(const w3r_word *source,size_t words,w3r_word *dest,size_t output_words,w3r_word tag); +bool CA_ReadMap(unsigned number,maptype *destination); +bool CA_InstallMap(const maptype *map); +bool CA_CacheMap(unsigned number); +const maptype *CA_Map(void); +void CA_UncacheMap(void); +#endif diff --git a/src/engine/ID_MM.c b/src/engine/ID_MM.c new file mode 100644 index 00000000..93a68d9f --- /dev/null +++ b/src/engine/ID_MM.c @@ -0,0 +1,98 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Port of WOLFSRC/ID_MM.C ownership/purge semantics. No segment relocation. */ +#include "ID_MM.h" +#include + +typedef struct mmblocktype { + memptr *useptr; + void *allocation; + size_t length; + unsigned purge; + bool locked; + struct mmblocktype *next; +} mmblocktype; + +static mmblocktype *mmhead; +static size_t used; + +static mmblocktype *MM_Find(memptr *baseptr) +{ + for (mmblocktype *block = mmhead; block; block = block->next) + if (block->useptr == baseptr) return block; + return NULL; +} + +void MM_Shutdown(void) +{ + while (mmhead) (void)MM_FreePtr(mmhead->useptr); +} + +void MM_Startup(void) +{ + MM_Shutdown(); +} + +bool MM_GetPtr(memptr *baseptr, size_t size) +{ + mmblocktype *block; + if (!baseptr || *baseptr || !size || size > MM_MAX_BYTES) return false; + if (size > MM_MAX_BYTES - used) MM_SortMem(); + if (size > MM_MAX_BYTES - used) return false; + block = calloc(1, sizeof(*block)); + if (!block) return false; + block->allocation = calloc(1, size); + if (!block->allocation) { free(block); return false; } + block->useptr = baseptr; + block->length = size; + block->next = mmhead; + mmhead = block; + *baseptr = block->allocation; + used += size; + return true; +} + +bool MM_FreePtr(memptr *baseptr) +{ + mmblocktype **link = &mmhead; + while (*link) { + mmblocktype *block = *link; + if (block->useptr == baseptr) { + *link = block->next; + used -= block->length; + free(block->allocation); + *baseptr = NULL; + free(block); + return true; + } + link = &block->next; + } + return false; +} + +bool MM_SetPurge(memptr *baseptr, unsigned purge) +{ + mmblocktype *block = MM_Find(baseptr); + if (!block || purge > 3) return false; + block->purge = purge; + return true; +} + +bool MM_SetLock(memptr *baseptr, bool locked) +{ + mmblocktype *block = MM_Find(baseptr); + if (!block) return false; + block->locked = locked; + return true; +} + +void MM_SortMem(void) +{ + mmblocktype *block = mmhead; + while (block) { + mmblocktype *next = block->next; + if (!block->locked && block->purge) (void)MM_FreePtr(block->useptr); + block = next; + } +} + +size_t MM_TotalBytes(void) { return used; } diff --git a/src/engine/ID_MM.h b/src/engine/ID_MM.h new file mode 100644 index 00000000..d40163e6 --- /dev/null +++ b/src/engine/ID_MM.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Portable slice of WOLFSRC/ID_MM.H: owner handles replace DOS segments. */ +#ifndef ID_MM_H +#define ID_MM_H +#include +#include + +typedef void *memptr; +#define MM_MAX_BYTES ((size_t)64 * 1024 * 1024) + +void MM_Startup(void); +void MM_Shutdown(void); +/* Handles must remain at a stable address until freed/shutdown. */ +bool MM_GetPtr(memptr *baseptr, size_t size); +bool MM_FreePtr(memptr *baseptr); +bool MM_SetPurge(memptr *baseptr, unsigned purge); +bool MM_SetLock(memptr *baseptr, bool locked); +void MM_SortMem(void); +size_t MM_TotalBytes(void); +#endif diff --git a/src/engine/ID_OPL.c b/src/engine/ID_OPL.c new file mode 100644 index 00000000..79038786 --- /dev/null +++ b/src/engine/ID_OPL.c @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Compile the pinned MIT dependency once, outside CART's recursive src scan. + Keep upstream warnings separate from the strict port; see third_party README. */ +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#pragma GCC diagnostic ignored "-Wsign-conversion" +#pragma GCC diagnostic ignored "-Wshadow" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wpedantic" +#endif +#include "../../third_party/emu8950/emu8950.c" +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#endif diff --git a/src/engine/ID_OPL_ADPCM.c b/src/engine/ID_OPL_ADPCM.c new file mode 100644 index 00000000..77e0efdb --- /dev/null +++ b/src/engine/ID_OPL_ADPCM.c @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Compile the pinned MIT dependency once, outside CART's recursive src scan. + Keep upstream warnings separate from the strict port; see third_party README. */ +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#pragma GCC diagnostic ignored "-Wsign-conversion" +#pragma GCC diagnostic ignored "-Wshadow" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wpedantic" +#endif +#include "../../third_party/emu8950/emuadpcm.c" +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#endif diff --git a/src/engine/ID_PM.c b/src/engine/ID_PM.c new file mode 100644 index 00000000..3e866bbb --- /dev/null +++ b/src/engine/ID_PM.c @@ -0,0 +1,90 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* ID_PM.C PML_OpenPageFile/PM_GetPage, portable heap cache instead of EMS/XMS. */ +#include "ID_PM.h" +#include "ID_FILE.h" +#include "ID_CA.h" +#include "platform/data_file.h" +#include +#include +#define PM_MAX_PAGES 4096 +unsigned ChunksInFile,PMSpriteStart,PMSoundStart; +static FILE *PageFile; +static uint32_t offsets[PM_MAX_PAGES]; +static uint16_t lengths[PM_MAX_PAGES]; +static memptr cache[PM_MAX_PAGES]; +void PM_Shutdown(void) +{ + for (unsigned i=0;i32*1024*1024 || fseek(PageFile,0,SEEK_SET)) goto bad; + if (fread(header,1,6,PageFile)!=6) goto bad; + ChunksInFile=CA_LE16(header); PMSpriteStart=CA_LE16(header+2); PMSoundStart=CA_LE16(header+4); + if (!ChunksInFile || ChunksInFile>PM_MAX_PAGES || PMSpriteStart<8 || PMSpriteStart>PMSoundStart || PMSoundStart>ChunksInFile) goto bad; + size_t end=6+(size_t)ChunksInFile*6; + if (end>(size_t)size || fread(directory,1,end-6,PageFile)!=end-6) goto bad; + size_t previous=end; + for (unsigned i=0;i(size_t)size || len>(size_t)size-off || (i=ChunksInFile || !offsets[page] || !lengths[page]) { (void)CA_Fail("Invalid/sparse VSWAP page %u",page); return NULL; } + if (!cache[page]) { + if (!MM_GetPtr(&cache[page],lengths[page])) { (void)CA_Fail("VSWAP cache allocation failed"); return NULL; } + if (fseek(PageFile,(long)offsets[page],SEEK_SET) || fread(cache[page],1,lengths[page],PageFile)!=lengths[page]) { + (void)MM_FreePtr(&cache[page]); (void)CA_Fail("Truncated VSWAP page"); return NULL; + } + } + if (length) *length=lengths[page]; + return cache[page]; +} +bool PM_DecodeSprite(unsigned sprite,w3r_byte pixels[4096],w3r_byte opaque[4096]) +{ + size_t length; + if (sprite>=PMSoundStart-PMSpriteStart || !pixels || !opaque) return CA_Fail("Invalid sprite number"); + const w3r_byte *page=PM_GetPage(PMSpriteStart+sprite,&length); + if (!page || length<4) return CA_Fail("Truncated sprite header"); + unsigned left=CA_LE16(page),right=CA_LE16(page+2); + if (left>right || right>=64 || length<4+(right-left+1)*2) return CA_Fail("Invalid sprite column table"); + memset(pixels,0,4096); memset(opaque,0,4096); + for (unsigned x=left;x<=right;++x) { + size_t command=CA_LE16(page+4+(x-left)*2); unsigned last=0; + if (command<4+(right-left+1)*2) return CA_Fail("Sprite command inside column table"); + for (;;) { + if (command>length || length-command<2) return CA_Fail("Truncated sprite posts"); + unsigned end=CA_LE16(page+command); command+=2; + if (!end) break; + if (length-command<4) return CA_Fail("Truncated sprite post"); + unsigned raw=CA_LE16(page+command),start=CA_LE16(page+command+2); command+=4; + int data=(raw&0x8000) ? (int)raw-65536 : (int)raw; + if ((start|end)&1U || start>=end || end>128 || start/2=length) return CA_Fail("Sprite pixel outside page"); + pixels[y*64+x]=page[at]; opaque[y*64+x]=1; + } + last=end/2; + } + } + return true; +} diff --git a/src/engine/ID_PM.h b/src/engine/ID_PM.h new file mode 100644 index 00000000..3b465ffe --- /dev/null +++ b/src/engine/ID_PM.h @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef ID_PM_H +#define ID_PM_H +#include "w3r_types.h" +#include +#include +extern unsigned ChunksInFile,PMSpriteStart,PMSoundStart; +bool PM_Startup(void); +bool PM_Ready(void); +void PM_Shutdown(void); +const w3r_byte *PM_GetPage(unsigned page,size_t *length); +bool PM_DecodeSprite(unsigned sprite,w3r_byte pixels[4096],w3r_byte opaque[4096]); +bool PM_PagePresent(unsigned page); +bool PM_PageCached(unsigned page); +#endif diff --git a/src/engine/ID_SD.c b/src/engine/ID_SD.c new file mode 100644 index 00000000..a16bfb73 --- /dev/null +++ b/src/engine/ID_SD.c @@ -0,0 +1,309 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Native port of ID_SD.C/ID_SD_A.ASM: IMF, AL effects and SB Pro priorities. + No DOS interrupts/devices: a rational sample clock services the original + 700/140 Hz schedules. The chip is shared, including channel-zero writes. */ +#include "ID_SD.h" +#include "ID_FILE.h" +#include "ID_CA.h" +#include "../../third_party/emu8950/emu8950.h" +#include +#include "platform/data_file.h" +#define AUDIO_CHUNKS 288U +#define MUSIC_BASE 261U +#define DIGI_COUNT 46U +static memptr header,archive,swap; +static size_t header_size,archive_size,swap_size; +static struct { const uint8_t *data; size_t size; } chunks[AUDIO_CHUNKS],digi[DIGI_COUNT]; +static memptr samples[DIGI_COUNT]; +static const int digimap[LASTSOUND]={ + [HALTSND]=1,[DOGBARKSND]=2,[CLOSEDOORSND]=3,[OPENDOORSND]=4, + [ATKMACHINEGUNSND]=5,[ATKPISTOLSND]=6,[ATKGATLINGSND]=7,[SCHUTZADSND]=8, + [GUTENTAGSND]=9,[MUTTISND]=10,[BOSSFIRESND]=11,[SSFIRESND]=12, + [DEATHSCREAM1SND]=13,[DEATHSCREAM2SND]=14,[DEATHSCREAM3SND]=14, + [TAKEDAMAGESND]=15,[PUSHWALLSND]=16,[DOGDEATHSND]=17,[AHHHGSND]=18, + [DIESND]=19,[EVASND]=20,[LEBENSND]=21,[NAZIFIRESND]=22,[SLURPIESND]=23, + [TOT_HUNDSND]=24,[MEINGOTTSND]=25,[SCHABBSHASND]=26,[HITLERHASND]=27, + [SPIONSND]=28,[NEINSOVASSND]=29,[DOGATTACKSND]=30,[LEVELDONESND]=31, + [MECHSTEPSND]=32,[YEAHSND]=33,[SCHEISTSND]=34,[DEATHSCREAM4SND]=35, + [DEATHSCREAM5SND]=36,[DONNERSND]=37,[EINESND]=38,[ERLAUBENSND]=39, + [DEATHSCREAM6SND]=40,[DEATHSCREAM7SND]=41,[DEATHSCREAM8SND]=42, + [DEATHSCREAM9SND]=43,[KEINSND]=44,[MEINSND]=45,[ROSESND]=46 +}; /* zero = no mapping; other entries = original sample index + 1. */ +static uint64_t output_generation; +void SD_FlushOutput(void) { ++output_generation; } +uint64_t SD_OutputGeneration(void) { return output_generation; } +static OPL *chip; +static unsigned output_rate,music_volume=70,effects_volume=85; +static bool music_enabled=true,effects_enabled=true,digitized_mode,music_paused; + +static sd_status status; +void SD_SetDigitizedMode(bool enabled) +{ + digitized_mode=enabled;status.digitized=-1;status.digi_priority=0; +} +bool SD_DigitizedMode(void) { return digitized_mode; } +static uint64_t phase,music_time,next_event,digi_phase,chip_phase; +static int32_t chip_previous[2],chip_next[2]; +static size_t music_pos,fx_pos,fx_length; +static unsigned fx_divider,fx_block; +static const uint8_t *fx_data; +static void Write(unsigned reg,unsigned value) +{ + status.registers[reg]=(uint8_t)value;++status.writes; + OPL_writeReg(chip,reg,(uint8_t)value); +} +static void Gains(void) +{ + if (!chip) return; + for (unsigned ch=0;ch<14;++ch) { + float volume=(float)(ch==0 ? (effects_enabled?effects_volume:0) : (music_enabled && !music_paused?music_volume:0))/100.0f; + float pan[2]={volume,volume};OPL_setPanFine(chip,ch,pan); + } +} +void SD_SetVolumes(unsigned music,unsigned effects) +{ + music_volume=music>100?100:music;effects_volume=effects>100?100:effects;Gains(); +} +void SD_GetSettings(unsigned *music,unsigned *effects,bool *music_on,bool *effects_on) +{ + if (music) *music=music_volume; + if (effects) *effects=effects_volume; + if (music_on) *music_on=music_enabled; + if (effects_on) *effects_on=effects_enabled; +} +bool SD_Ready(void) { return chip!=NULL; } +void SD_GetStatus(sd_status *out) { if(out) *out=status; } +void SD_StopSound(void) +{ + fx_data=NULL;fx_pos=fx_length=0; + status.sound=status.digitized=-1;status.sound_priority=status.digi_priority=0; + if(chip) Write(0xb0,0); +} +static void MusicOff(void) +{ + if(!chip) return; + Write(0xbd,0); + for(unsigned i=1;i<=10;++i) Write(0xb0+i,0); +} +bool SD_MusicPaused(void) { return music_paused; } +void SD_SetMusicPaused(bool paused) +{ + if(paused && !music_paused) MusicOff(); + music_paused=paused;Gains(); +} +void SD_StartMusic(int track) +{ + if(!chip) return; + music_paused=false;Gains();MusicOff();status.music=track>=0 && track<27?track:-1; + music_pos=0;music_time=next_event=0; +} +void SD_SetEnabled(bool music,bool effects) +{ + bool restart=!music_enabled && music; + if(music_enabled && !music) MusicOff(); + music_enabled=music;effects_enabled=effects; + if(restart) SD_StartMusic(status.music); + if(!effects) SD_StopSound(); + Gains(); +} +void SD_Shutdown(void) +{ + if(chip) { OPL_delete(chip);chip=NULL; } + for(unsigned i=0;iend || end>archive_size) return CA_Fail("Invalid AUDIOT.WL6 chunk %u bounds",i); + chunks[i].data=a+start;chunks[i].size=end-start; + } + for(unsigned i=0;in-23 || !CA_LE32(s) || !(s[12]|s[13])) + return CA_Fail("Malformed AdLib sound %u",i); + s=chunks[i].data;n=chunks[i].size; + if(n<6 || CA_LE32(s)>n-6) return CA_Fail("Malformed PC sound %u",i); + } + for(unsigned i=MUSIC_BASE;in-2) + return CA_Fail("Malformed WL6 IMF music %u",i-MUSIC_BASE); + /* Original MusicGroup is length-prefixed; it is not generic IMF type 0. */ + } + return true; +} +static bool LoadDigi(void) +{ + if(!CA_ReadDataFile("VSWAP.WL6",&swap,&swap_size)) return false; + const uint8_t *s=swap;unsigned count,start; + if(swap_size<6) goto bad; + count=CA_LE16(s);start=CA_LE16(s+4); + size_t directory=6+(size_t)count*6,previous=directory; + if(count<2 || count>4096 || start>=count-1 || CA_LE16(s+2)>start || directory>swap_size) goto bad; + for(unsigned p=0;pswap_size || length>swap_size-offset) goto bad; + previous=offset+length; + } + size_t tableoff=CA_LE32(s+6+(count-1)*4),tablelen=CA_LE16(s+6+count*4+(count-1)*2); + if(!tableoff || tablelen=count-1 || !MM_GetPtr(&samples[i],left)) goto bad; + digi[i].data=samples[i];digi[i].size=left; + while(left) { + if(page>=count-1) goto bad; + size_t offset=CA_LE32(s+6+page*4),length=CA_LE16(s+6+count*4+page*2); + size_t copy=left>4096?4096:left; + if(!offset || length192000) return CA_Fail("Unsupported audio sample rate"); + if(!LoadAudio() || !LoadDigi()) { SD_Shutdown();return false; } + /* Use the native chip rate. Resample below with integer phase; avoids + allocations in the synthesiser's optional rate converter. */ + chip=OPL_new(3579545,49716); + if(!chip) { SD_Shutdown();return CA_Fail("Cannot allocate OPL2 synthesiser"); } + OPL_setChipType(chip,2);OPL_reset(chip);Write(1,0x20);Write(8,0); + output_rate=rate;phase=rate;chip_phase=rate;fx_divider=0;digi_phase=0;music_pos=0; + memset(chip_previous,0,sizeof(chip_previous));memset(chip_next,0,sizeof(chip_next)); + Gains();return true; +} +void SD_SetPosition(unsigned left,unsigned right) +{ + status.left=left>15?15:left;status.right=right>15?15:right; +} +bool SD_IsDigitizedSound(soundnames sound) { return digitized_mode && (unsigned)sound=LASTSOUND) return false; + const uint8_t *s=chunks[87+(unsigned)sound].data;unsigned priority=CA_LE16(s+4); + int mapped=digitized_mode?digimap[sound]-1:-1; + if(mapped>=0) { + if(priority=0 && music_enabled && !music_paused) { + const uint8_t *song=chunks[MUSIC_BASE+(unsigned)status.music].data; + size_t length=CA_LE16(song); + while(music_pos=output_rate) { phase-=output_rate;Tick(); } + while(chip_phase>=output_rate) { + chip_phase-=output_rate;memcpy(chip_previous,chip_next,sizeof(chip_next)); + OPL_calcStereo(chip,chip_next); + } + int32_t l=chip_previous[0]+(int32_t)((int64_t)(chip_next[0]-chip_previous[0])*(int64_t)chip_phase/(int64_t)output_rate); + int32_t r=chip_previous[1]+(int32_t)((int64_t)(chip_next[1]-chip_previous[1])*(int64_t)chip_phase/(int64_t)output_rate); + /* Match the low-level OPL output to the 16-bit PCM voice range. + Apply gain in the wide accumulator, after chip synthesis, so the + chip's int16 mixer cannot wrap. Leave digitized samples unchanged. */ + l*=4;r*=4; + phase+=700;chip_phase+=49716; + if(status.digitized>=0) { + unsigned d=(unsigned)status.digitized;size_t at=(size_t)(digi_phase/(UINT64_C(142)*output_rate)); + if(at>=digi[d].size) { status.digitized=-1;status.digi_priority=0; } + else { + int32_t sample=((int32_t)digi[d].data[at]-128)*256; + unsigned gain=effects_enabled?effects_volume:0; + l+=(int32_t)((int64_t)sample*gain*(15-status.left)/1500); + r+=(int32_t)((int64_t)sample*gain*(15-status.right)/1500); + /* Original SB constant: 256 - floor(1000000/7000) = 114. + Therefore DAC rate is 1000000/142, not exactly 7000 Hz. */ + digi_phase+=1000000; + } + } + stereo[i*2]=(int16_t)(l>32767?32767:l< -32768?-32768:l); + stereo[i*2+1]=(int16_t)(r>32767?32767:r< -32768?-32768:r); + ++status.frames; + } +} +int SD_LevelMusic(unsigned episode,unsigned floor) +{ + static const int songs[60]={3,11,9,12,3,11,9,12,2,0, 8,18,17,4,8,18,4,17,2,1, + 6,20,22,21,6,20,22,21,19,26, 3,11,9,12,3,11,9,12,2,0, + 8,18,17,4,8,18,4,17,2,1, 6,20,22,21,6,20,22,21,19,15}; + return episode<6 && floor<10?songs[episode*10+floor]:-1; +} + +unsigned SD_SoundTicks(soundnames sound) +{ + if((unsigned)sound>=LASTSOUND) return 0; + if(chip) return (unsigned)((CA_LE32(chunks[87+(unsigned)sound].data)+1U)/2U); + /* Read metadata only when PCM is disabled. No synthesiser/device startup, + persistent cache, audio thread IO or gameplay RNG is involved. */ + FILE *h=CA_OpenDataFile(CA_DataDirectory(),"AUDIOHED.WL6"); + FILE *a=CA_OpenDataFile(CA_DataDirectory(),"AUDIOT.WL6"); + unsigned result=0;uint8_t offsets[8],common[6];long size; + if(h && a && !fseek(h,(long)(87+(unsigned)sound)*4,SEEK_SET) && fread(offsets,1,8,h)==8 && + !fseek(a,0,SEEK_END) && (size=ftell(a))>=0) { + uint32_t start=CA_LE32(offsets),end=CA_LE32(offsets+4); + if(start<=end && end<=(unsigned long)size && end-start>=23 && + !fseek(a,(long)start,SEEK_SET) && fread(common,1,6,a)==6 && CA_LE32(common)<=end-start-23) + result=(unsigned)((CA_LE32(common)+1U)/2U); + } + if(h) (void)fclose(h); + if(a) (void)fclose(a); + return result; +} diff --git a/src/engine/ID_SD.h b/src/engine/ID_SD.h new file mode 100644 index 00000000..a1f962b1 --- /dev/null +++ b/src/engine/ID_SD.h @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef ID_SD_H +#define ID_SD_H +#include "WL_SOUND.h" +#include +#include +#include +/* All APIs run on the main thread. SDL consumes copied PCM, never this state. */ +bool SD_Startup(unsigned rate); +void SD_Shutdown(void); +bool SD_Ready(void); +/* Logical original mode, independent of SDL availability and mute. Configure + before a level starts; front end selects digitized + AdLib by default. */ +void SD_SetDigitizedMode(bool enabled); +bool SD_DigitizedMode(void); +void SD_SetMusicPaused(bool paused); /* Transient DOS Pause; preserves preferences/position. */ +bool SD_MusicPaused(void); +void SD_StartMusic(int track); /* -1 stops music; original indices 0..26. */ +int SD_LevelMusic(unsigned episode,unsigned floor); +bool SD_IsDigitizedSound(soundnames sound); +bool SD_PlaySound(soundnames sound,unsigned left,unsigned right); +void SD_StopSound(void); +void SD_FlushOutput(void); +uint64_t SD_OutputGeneration(void); +void SD_SetPosition(unsigned left,unsigned right); +void SD_Render(int16_t *stereo,size_t frames); +void SD_SetVolumes(unsigned music,unsigned effects); /* 0..100 */ +void SD_SetEnabled(bool music,bool effects); +void SD_GetSettings(unsigned *music,unsigned *effects,bool *music_on,bool *effects_on); +/* Read-only diagnostics also permit scheduling/priority regressions. */ +typedef struct { + uint64_t frames,ticks,loops,writes; + int music,sound,digitized; + unsigned sound_priority,digi_priority,left,right; + uint8_t registers[256]; +} sd_status; +void SD_GetStatus(sd_status *status); +/* Original logical AL wait in 70-Hz presentation tics, independent of device. */ +unsigned SD_SoundTicks(soundnames sound); +#endif diff --git a/src/engine/ID_TIME.h b/src/engine/ID_TIME.h new file mode 100644 index 00000000..3afc2350 --- /dev/null +++ b/src/engine/ID_TIME.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef ID_TIME_H +#define ID_TIME_H +#include +/* TickBase is 70 in ID_SD.H. Preserve fractional nanoseconds without drift. */ +static inline uint64_t TimeCount_FromNS(uint64_t ns) +{ + return (ns / UINT64_C(1000000000)) * 70 + (ns % UINT64_C(1000000000)) * 70 / UINT64_C(1000000000); +} +#endif diff --git a/src/engine/ID_US_1.c b/src/engine/ID_US_1.c new file mode 100644 index 00000000..14dd8c63 --- /dev/null +++ b/src/engine/ID_US_1.c @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* ID_US_1.C, original user manager by Jason Blochowiak. + US_Print now accepts immutable strings without modifying them. */ +#include "ID_US_1.h" +#include "ID_VH.h" +#include "ID_CA.h" +#include +int PrintX, PrintY, WindowX; +bool US_Print(const char *text) +{ + if (!text) return CA_Fail("Missing UI text"); + char line[256]; + while (*text) { + const char *end = strchr(text, '\n'); + size_t size = end ? (size_t)(end - text) : strlen(text); + int width, height; + if (size >= sizeof(line)) return CA_Fail("UI text line too long"); + memcpy(line, text, size); line[size] = 0; + if (!VW_MeasurePropString(line, &width, &height)) return false; + px = PrintX; py = PrintY; + if (!VW_DrawPropString(line)) return false; + if (!end) { PrintX += width; break; } + PrintX = WindowX; PrintY += height; text = end + 1; + } + return true; +} diff --git a/src/engine/ID_US_1.h b/src/engine/ID_US_1.h new file mode 100644 index 00000000..f972024d --- /dev/null +++ b/src/engine/ID_US_1.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef ID_US_1_H +#define ID_US_1_H +#include +extern int PrintX, PrintY, WindowX; +bool US_Print(const char *text); +void US_InitRndT(unsigned seed); +int US_RndT(void); +unsigned US_RndIndex(void); +#endif diff --git a/src/engine/ID_US_A.c b/src/engine/ID_US_A.c new file mode 100644 index 00000000..527f3608 --- /dev/null +++ b/src/engine/ID_US_A.c @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WOLFSRC/ID_US_A.ASM: increment-before-read, wrapping 8-bit RNG. */ +#include "ID_US_1.h" +static const unsigned char rndtable[256]={ + 0,8,109,220,222,241,149,107,75,248,254,140,16,66,74,21, + 211,47,80,242,154,27,205,128,161,89,77,36,95,110,85,48, + 212,140,211,249,22,79,200,50,28,188,52,140,202,120,68,145, + 62,70,184,190,91,197,152,224,149,104,25,178,252,182,202,182, + 141,197,4,81,181,242,145,42,39,227,156,198,225,193,219,93, + 122,175,249,0,175,143,70,239,46,246,163,53,163,109,168,135, + 2,235,25,92,20,145,138,77,69,166,78,176,173,212,166,113, + 94,161,41,50,239,49,111,164,70,60,2,37,171,75,136,156, + 11,56,42,146,138,229,73,146,77,61,98,196,135,106,63,197, + 195,86,96,203,113,101,170,247,181,113,80,250,108,7,255,237, + 129,226,79,107,112,166,103,241,24,223,239,120,198,58,60,82, + 128,3,184,66,143,224,145,224,81,206,163,45,63,90,168,114, + 59,33,159,95,28,139,123,98,125,196,15,70,194,253,54,14, + 109,226,71,17,161,93,186,87,244,138,20,52,123,251,26,36, + 17,46,52,231,232,76,31,221,84,37,216,165,212,106,197,242, + 98,43,39,175,254,145,190,84,118,222,187,136,120,163,236,249 +}; +static unsigned rndindex; +void US_InitRndT(unsigned seed) { rndindex=seed&255U; } +int US_RndT(void) { rndindex=(rndindex+1U)&255U;return rndtable[rndindex]; } + +unsigned US_RndIndex(void) { return rndindex; } diff --git a/src/engine/ID_VH.c b/src/engine/ID_VH.c new file mode 100644 index 00000000..d3320ae2 --- /dev/null +++ b/src/engine/ID_VH.c @@ -0,0 +1,75 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* ID_VH.C drawing/measurement: original planar pictures and row-major fonts. */ +#include "ID_VH.h" +#include "ID_CA.h" +#include +#include +int px, py, fontnumber; +w3r_byte fontcolor; +static unsigned LE16(const w3r_byte *p) { return (unsigned)p[0] | ((unsigned)p[1] << 8); } + +bool VW_ValidateFont(int number) +{ + if (number < 0 || number >= NUMFONT) return CA_Fail("Invalid font number"); + int chunk = STARTFONT + number; + if (!CA_CacheGrChunk(chunk)) return false; + const w3r_byte *raw = grsegs[chunk]; + size_t length = grsizes[chunk]; + if (length < 770 || !LE16(raw) || LE16(raw) > 200) return CA_Fail("Malformed font header"); + for (size_t i = 0; i < 256; ++i) { + size_t width = raw[514 + i], offset = LE16(raw + 2 + i * 2); + size_t pixels = width * LE16(raw); + if (width && (offset < 770 || offset > length || pixels > length - offset)) + return CA_Fail("Font glyph %zu extends outside its chunk", i); + } + return true; +} + +bool VWB_DrawPic(int x, int y, int chunk) +{ + if (chunk < STARTPICS || chunk >= STARTPICS + NUMPICS) return CA_Fail("Invalid picture index"); + if (!CA_CacheGrChunk(chunk)) return false; + pictabletype pic = pictable[chunk - STARTPICS]; + x &= ~7; /* Original buffered picture alignment, ID_VH.C. */ + return VL_MemToScreen(grsegs[chunk], grsizes[chunk], pic.width, pic.height, x, y) || + CA_Fail("Malformed picture dimensions/length or drawing bounds"); +} + +void VWB_Bar(int x, int y, int width, int height, w3r_byte color) +{ + if (width <= 0 || height <= 0 || x < 0 || y < 0 || x > 320 - width || y > 200 - height) return; + for (int row = y; row < y + height; ++row) memset(framebuffer + row * 320 + x, color, (size_t)width); +} +void VWB_Hlin(int x1, int x2, int y, w3r_byte color) { if (x1 >= 0 && x2 >= x1 && x2 < 320) VWB_Bar(x1, y, x2 - x1 + 1, 1, color); } +void VWB_Vlin(int y1, int y2, int x, w3r_byte color) { if (y1 >= 0 && y2 >= y1 && y2 < 200) VWB_Bar(x, y1, 1, y2 - y1 + 1, color); } + +bool VW_MeasurePropString(const char *text, int *width, int *height) +{ + if (!text || !width || !height || !VW_ValidateFont(fontnumber)) return false; + const w3r_byte *font = grsegs[STARTFONT + fontnumber]; + *width = 0; *height = (int)LE16(font); + for (const unsigned char *s = (const unsigned char *)text; *s; ++s) { + if (*width > 32000) return CA_Fail("Font string too wide"); + *width += font[514 + *s]; + } + return true; +} + +bool VW_DrawPropString(const char *text) +{ + int width, height; + if (!VW_MeasurePropString(text, &width, &height)) return false; + if (px < -32000 || px > 32000 || py < -200 || py > 200) return CA_Fail("Text origin out of bounds"); + const w3r_byte *font = grsegs[STARTFONT + fontnumber]; + for (const unsigned char *s = (const unsigned char *)text; *s; ++s) { + int step = font[514 + *s]; + if (!step) continue; + const w3r_byte *source = font + LE16(font + 2 + (size_t)*s * 2); + for (int y = 0; y < height; ++y) + for (int x = 0; x < step; ++x) + if (px + x >= 0 && px + x < 320 && py + y >= 0 && py + y < 200 && source[y * step + x]) + framebuffer[(py + y) * 320 + px + x] = fontcolor; + px += step; + } + return true; +} diff --git a/src/engine/ID_VH.h b/src/engine/ID_VH.h new file mode 100644 index 00000000..668747c3 --- /dev/null +++ b/src/engine/ID_VH.h @@ -0,0 +1,14 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef ID_VH_H +#define ID_VH_H +#include "ID_VL.h" +extern int px, py, fontnumber; +extern w3r_byte fontcolor; +bool VW_ValidateFont(int number); +bool VWB_DrawPic(int x, int y, int chunk); +bool VW_MeasurePropString(const char *text, int *width, int *height); +bool VW_DrawPropString(const char *text); +void VWB_Bar(int x, int y, int width, int height, w3r_byte color); +void VWB_Hlin(int x1, int x2, int y, w3r_byte color); +void VWB_Vlin(int y1, int y2, int x, w3r_byte color); +#endif diff --git a/src/engine/ID_VL.c b/src/engine/ID_VL.c new file mode 100644 index 00000000..22e684b4 --- /dev/null +++ b/src/engine/ID_VL.c @@ -0,0 +1,87 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WOLFSRC/ID_VL.C: VGA planes and DAC writes translated to portable buffers. */ +#include "ID_VL.h" +#include + +w3r_byte framebuffer[VL_PIXELS]; +w3r_byte palette[768]; +const w3r_byte gamepal[768] = { +#include "gamepal.inc" +}; + +bool VL_SetPalette(const w3r_byte *source, size_t length) +{ + if (!source || length != sizeof(palette)) return false; + for (size_t i = 0; i < length; ++i) if (source[i] > 63) return false; + memcpy(palette, source, length); + return true; +} + +bool VL_MemToScreen(const w3r_byte *source, size_t length, + int width, int height, int x, int y) +{ + size_t plane_size, row_size; + if (!source || width <= 0 || height <= 0 || width > W3R_SCREEN_WIDTH || + height > W3R_SCREEN_HEIGHT || width % 4 || x < 0 || y < 0 || + x > W3R_SCREEN_WIDTH - width || y > W3R_SCREEN_HEIGHT - height) + return false; + if (length != (size_t)width * (size_t)height) return false; + row_size = (size_t)width / 4; + plane_size = row_size * (size_t)height; + for (size_t plane = 0; plane < 4; ++plane) + for (size_t row = 0; row < (size_t)height; ++row) + for (size_t col = 0; col < row_size; ++col) + framebuffer[((size_t)y + row) * W3R_SCREEN_WIDTH + (size_t)x + col * 4 + plane] = + source[plane * plane_size + row * row_size + col]; + return true; +} + +bool VL_ConvertRGBA(w3r_byte *dest, size_t length) +{ + if (!dest || length < VL_PIXELS * 4) return false; + for (size_t i = 0; i < VL_PIXELS; ++i) { + size_t color = (size_t)framebuffer[i] * 3; + for (size_t channel = 0; channel < 3; ++channel) { + unsigned value = palette[color + channel]; + dest[i * 4 + channel] = (w3r_byte)((value << 2) | (value >> 4)); + } + dest[i * 4 + 3] = 255; + } + return true; +} + +/* ID_VL.C interpolation: orig + (target-orig)*i/steps, truncating toward zero. */ +static w3r_byte fade_from[768], fade_to[768]; +static uint64_t fade_start; +static unsigned fade_steps; +bool VL_Fading(void) { return fade_steps != 0; } +bool VL_FadeIn(const w3r_byte target[768], unsigned steps, uint64_t ticks) +{ + if (!target || steps > 1000) return false; + for (size_t i = 0; i < 768; ++i) if (target[i] > 63) return false; + memcpy(fade_from, palette, 768); memcpy(fade_to, target, 768); + fade_start = ticks; fade_steps = steps; + if (!steps) (void)VL_SetPalette(target, 768); + return true; +} +bool VL_FadeOut(unsigned red, unsigned green, unsigned blue, unsigned steps, uint64_t ticks) +{ + w3r_byte target[768]; + if (red > 63 || green > 63 || blue > 63) return false; + for (size_t i = 0; i < 768; i += 3) { + target[i] = (w3r_byte)red; target[i + 1] = (w3r_byte)green; target[i + 2] = (w3r_byte)blue; + } + return VL_FadeIn(target, steps, ticks); +} +void VL_FadeStep(uint64_t ticks) +{ + if (!fade_steps || ticks < fade_start) return; + uint64_t elapsed = ticks - fade_start; + if (elapsed >= fade_steps) { + (void)VL_SetPalette(fade_to, 768); fade_steps = 0; return; + } + for (size_t i = 0; i < 768; ++i) { + int original = fade_from[i], delta = (int)fade_to[i] - original; + palette[i] = (w3r_byte)(original + delta * (int)elapsed / (int)fade_steps); + } +} diff --git a/src/engine/ID_VL.h b/src/engine/ID_VL.h new file mode 100644 index 00000000..14bb2afc --- /dev/null +++ b/src/engine/ID_VL.h @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef ID_VL_H +#define ID_VL_H +#include "w3r_types.h" +#include +#include + +#define VL_PIXELS ((size_t)W3R_SCREEN_WIDTH * W3R_SCREEN_HEIGHT) +extern w3r_byte framebuffer[VL_PIXELS]; +extern w3r_byte palette[768]; /* Original 0..63 DAC values, RGB order. */ +extern const w3r_byte gamepal[768]; +bool VL_SetPalette(const w3r_byte *source, size_t length); +/* Four consecutive planes, width divisible by four; no partial writes on error. */ +bool VL_MemToScreen(const w3r_byte *source, size_t length, + int width, int height, int x, int y); +bool VL_ConvertRGBA(w3r_byte *dest, size_t length); +/* Incremental forms of the original palette fades, driven by 70 Hz tics. */ +bool VL_FadeIn(const w3r_byte target[768], unsigned steps, uint64_t ticks); +bool VL_FadeOut(unsigned red, unsigned green, unsigned blue, unsigned steps, uint64_t ticks); +void VL_FadeStep(uint64_t ticks); +bool VL_Fading(void); +#endif diff --git a/src/engine/WL_ACT1.c b/src/engine/WL_ACT1.c new file mode 100644 index 00000000..a0a1f8cc --- /dev/null +++ b/src/engine/WL_ACT1.c @@ -0,0 +1,148 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WOLFSRC/WL_ACT1.C OpenDoor/CloseDoor/OperateDoor/MoveDoors, one tic at a + time. Original marked-grid/center-row checks protect closing doors; key + inventory gates locked doors. ConnectAreas rebuilds connectivity in the one-tic game loop. */ +#include "WL_DEF.h" +#include +static void DoorSound(soundnames sound,const doorobj_t *d) +{ + int area=areaMap[d->x][d->y]; + if(area<0 || area>=37 || !areabyplayer[area]) return; + objtype position={0};position.x=(int32_t)d->x*TILEGLOBAL+32768;position.y=(int32_t)d->y*TILEGLOBAL+32768; + GameSound(sound,&position); +} +bool DoorSolid(unsigned door) { return door>=doornum || doorobjlist[door].action!=dr_open; } +void OpenDoor(unsigned door) +{ + if (door>=doornum) return; + doorobj_t *d=&doorobjlist[door]; + if (d->action==dr_open) d->ticcount=0; + else d->action=dr_opening; +} +/* WL_ACT1.C CloseDoor uses the marked actor grid, including corpses. A + non-shootable actor can still obstruct a doorway in the DOS simulation. */ +static bool DoorOccupied(const doorobj_t *d) +{ + return actorat[d->x][d->y]!=NULL || + (player.tilex==(int)d->x && player.tiley==(int)d->y); +} +static bool PlayerBlocks(const doorobj_t *d) +{ + int x=(int)d->x,y=(int)d->y; + if (DoorOccupied(d)) return true; + if (d->vertical) { + if (player.tiley==y && ((player.x+MINDIST)/TILEGLOBAL==x || (player.x-MINDIST)/TILEGLOBAL==x)) return true; + const objtype *a=x>0?actorat[x-1][y]:NULL,*b=x<63?actorat[x+1][y]:NULL; + return (a && (a->x+MINDIST)/TILEGLOBAL==x) || (b && (b->x-MINDIST)/TILEGLOBAL==x); + } + if (player.tilex==x && ((player.y+MINDIST)/TILEGLOBAL==y || (player.y-MINDIST)/TILEGLOBAL==y)) return true; + const objtype *a=y>0?actorat[x][y-1]:NULL,*b=y<63?actorat[x][y+1]:NULL; + return (a && (a->y+MINDIST)/TILEGLOBAL==y) || (b && (b->y-MINDIST)/TILEGLOBAL==y); +} + +void CloseDoor(unsigned door) +{ + if (door>=doornum) return; + doorobj_t *d=&doorobjlist[door]; + /* Original actorat marker stays solid throughout opening/closing. */ + if (DoorSolid(door) || PlayerBlocks(d)) return; + DoorSound(CLOSEDOORSND,d);d->action=dr_closing; +} +void OperateDoor(unsigned door) +{ + if (door>=doornum) return; + doorobj_t *d=&doorobjlist[door]; + if (d->lock>=1 && d->lock<=4 && !(gamestate.keys & (1 << (d->lock-1)))) { GameSound(NOWAYSND,NULL);return; } + if (d->action==dr_closed || d->action==dr_closing) OpenDoor(door); + else CloseDoor(door); +} +void MoveDoors(void) +{ + for (unsigned i=0;iaction==dr_open) { + /* Original signed 16-bit door timer, including blocked-door wrap. */ + d->ticcount=(d->ticcount+(unsigned)SimulationTics())&65535U; + if (d->ticcount>=300 && d->ticcount<32768) CloseDoor(i); + } else if (d->action==dr_opening) { + if(!d->position) DoorSound(OPENDOORSND,d); + unsigned position=(unsigned)d->position+1024U*(unsigned)SimulationTics(); + if (position>=65535) { position=65535;d->ticcount=0;d->action=dr_open; + /* DOS DoorOpening releases the destination reservation. */ + actorat[d->x][d->y]=NULL; } + d->position=(uint16_t)position; + } else if (d->action==dr_closing) { + if (DoorOccupied(d)) { OpenDoor(i);continue; } + if (d->position<=1024U*(unsigned)SimulationTics()) { d->position=0;d->action=dr_closed; } + else d->position=(uint16_t)(d->position-1024U*(unsigned)SimulationTics()); + } + } +} +/* WL_AGENT.C Cmd_Use cardinal facing, doors, pushwalls and elevators. */ +void Cmd_Use(void) +{ + int x=(int)player.tilex,y=(int)player.tiley; + if (player.angle<45 || player.angle>315) ++x; + else if (player.angle<135) --y; + else if (player.angle<225) --x; + else ++y; + if (x<0 || y<0 || x>=64 || y>=64) return; + unsigned tile=tilemap[x][y]; + int dir=player.angle<45 || player.angle>315 ? east : player.angle<135 ? north : player.angle<225 ? west : south; + if (pushable[x][y]) { PushWall(x,y,dir);return; } + if (tile==21 && (player.angle<45 || player.angle>315 || (player.angle>=135 && player.angle<225))) { + GameSound(LEVELDONESND,NULL); + ++tilemap[x][y]; /* Original elevator switch texture. */ + playstate=CA_Map()->planes[0][player.tiley*64+player.tilex]==107 ? ex_secretlevel : ex_completed; + } else if (tile&128) OperateDoor(tile&127); + else GameSound(DONOTHINGSND,NULL); +} + +/* WL_ACT1.C PushWall/MovePWalls. Runtime marker/area arrays replace writes + into cached map planes, so the disk map remains an immutable restart source. */ +unsigned pwallstate,pwallpos; +int pwallx,pwally,pwalldir; +bool pushable[64][64]; +static const int pushdx[8]={1,0,0,0,-1,0,0,0}; +static const int pushdy[8]={0,0,-1,0,0,0,1,0}; +void ResetPushwalls(void) +{ + pwallstate=pwallpos=0;pwallx=pwally=pwalldir=0; + memset(pushable,0,sizeof(pushable)); +} +static bool PushBlocked(int x,int y) +{ + return x<0 || y<0 || x>=64 || y>=64 || (tilemap[x][y] && tilemap[x][y]!=64) || staticblock[x][y] || actorat[x][y]; +} +void PushWall(int x,int y,int dir) +{ + if (pwallstate || x<=0 || y<=0 || x>=63 || y>=63 || + dir<0 || dir>=8 || (dir&1) || !pushable[x][y]) return; + unsigned tile=tilemap[x][y]; + if (!tile || tile>=64) return; + if(PushBlocked(x+pushdx[dir],y+pushdy[dir])) { GameSound(NOWAYSND,NULL);return; } + GameSound(PUSHWALLSND,NULL); + tilemap[x+pushdx[dir]][y+pushdy[dir]]=(w3r_byte)tile; + ++gamestate.secretcount;pwallx=x;pwally=y;pwalldir=dir; + pwallstate=1;pwallpos=0;tilemap[x][y]|=0xc0;pushable[x][y]=false; +} +void MovePWalls(void) +{ + if (!pwallstate) return; + unsigned oldblock=pwallstate/128; + pwallstate+=(unsigned)SimulationTics(); + if (pwallstate/128!=oldblock) { + unsigned tile=tilemap[pwallx][pwally]&63; + tilemap[pwallx][pwally]=0; + areaMap[pwallx][pwally]=areaMap[player.tilex][player.tiley]; + /* Stop after two tile crossings. Original >256 relied on multi-tic + steps overshooting 256; >= also handles exact one-tic boundaries. */ + if (pwallstate>=256) { pwallstate=0;return; } + pwallx+=pushdx[pwalldir];pwally+=pushdy[pwalldir]; + int nx=pwallx+pushdx[pwalldir],ny=pwally+pushdy[pwalldir]; + if (PushBlocked(nx,ny)) { pwallstate=0;return; } + tilemap[nx][ny]=(w3r_byte)tile; + tilemap[pwallx][pwally]=(w3r_byte)(tile|0xc0); + } + pwallpos=(pwallstate/2)&63U; +} diff --git a/src/engine/WL_ACT2.c b/src/engine/WL_ACT2.c new file mode 100644 index 00000000..2c22790b --- /dev/null +++ b/src/engine/WL_ACT2.c @@ -0,0 +1,752 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Ported from id Software WOLFSRC/WL_ACT2.C and WL_STATE.C. + Original source/licensing: WOLFSRC/ and docs/LICENSING.md. */ +#include "WL_DEF.h" +#include "ID_CA.h" +#include "ID_PM.h" +#include "ID_US_1.h" +#include +#include +#define tics SimulationTics() +#define PROJECTILESIZE INT32_C(0xc000) +#define PROJSIZE INT32_C(0x2000) + +statetype s_rocket = {true,SPR_ROCKET_1,3,T_Projectile,A_Smoke,&s_rocket}; +statetype s_smoke1 = {false,SPR_SMOKE_1,3,NULL,NULL,&s_smoke2}; +statetype s_smoke2 = {false,SPR_SMOKE_2,3,NULL,NULL,&s_smoke3}; +statetype s_smoke3 = {false,SPR_SMOKE_3,3,NULL,NULL,&s_smoke4}; +statetype s_smoke4 = {false,SPR_SMOKE_4,3,NULL,NULL,NULL}; +statetype s_boom1 = {false,SPR_BOOM_1,6,NULL,NULL,&s_boom2}; +statetype s_boom2 = {false,SPR_BOOM_2,6,NULL,NULL,&s_boom3}; +statetype s_boom3 = {false,SPR_BOOM_3,6,NULL,NULL,NULL}; +statetype s_schabbstand = {false,SPR_SCHABB_W1,0,T_Stand,NULL,&s_schabbstand}; +statetype s_schabbchase1 = {false,SPR_SCHABB_W1,10,T_Schabb,NULL,&s_schabbchase1s}; +statetype s_schabbchase1s = {false,SPR_SCHABB_W1,3,NULL,NULL,&s_schabbchase2}; +statetype s_schabbchase2 = {false,SPR_SCHABB_W2,8,T_Schabb,NULL,&s_schabbchase3}; +statetype s_schabbchase3 = {false,SPR_SCHABB_W3,10,T_Schabb,NULL,&s_schabbchase3s}; +statetype s_schabbchase3s = {false,SPR_SCHABB_W3,3,NULL,NULL,&s_schabbchase4}; +statetype s_schabbchase4 = {false,SPR_SCHABB_W4,8,T_Schabb,NULL,&s_schabbchase1}; +statetype s_schabbdeathcam = {false,SPR_SCHABB_W1,1,NULL,NULL,&s_schabbdie1}; +statetype s_schabbdie1 = {false,SPR_SCHABB_W1,10,NULL,A_DeathScream,&s_schabbdie2}; +statetype s_schabbdie2 = {false,SPR_SCHABB_W1,10,NULL,NULL,&s_schabbdie3}; +statetype s_schabbdie3 = {false,SPR_SCHABB_DIE1,10,NULL,NULL,&s_schabbdie4}; +statetype s_schabbdie4 = {false,SPR_SCHABB_DIE2,10,NULL,NULL,&s_schabbdie5}; +statetype s_schabbdie5 = {false,SPR_SCHABB_DIE3,10,NULL,NULL,&s_schabbdie6}; +statetype s_schabbdie6 = {false,SPR_SCHABB_DEAD,20,NULL,A_StartDeathCam,&s_schabbdie6}; +statetype s_schabbshoot1 = {false,SPR_SCHABB_SHOOT1,30,NULL,NULL,&s_schabbshoot2}; +statetype s_schabbshoot2 = {false,SPR_SCHABB_SHOOT2,10,NULL,T_SchabbThrow,&s_schabbchase1}; +statetype s_needle1 = {false,SPR_HYPO1,6,T_Projectile,NULL,&s_needle2}; +statetype s_needle2 = {false,SPR_HYPO2,6,T_Projectile,NULL,&s_needle3}; +statetype s_needle3 = {false,SPR_HYPO3,6,T_Projectile,NULL,&s_needle4}; +statetype s_needle4 = {false,SPR_HYPO4,6,T_Projectile,NULL,&s_needle1}; +statetype s_giftstand = {false,SPR_GIFT_W1,0,T_Stand,NULL,&s_giftstand}; +statetype s_giftchase1 = {false,SPR_GIFT_W1,10,T_Gift,NULL,&s_giftchase1s}; +statetype s_giftchase1s = {false,SPR_GIFT_W1,3,NULL,NULL,&s_giftchase2}; +statetype s_giftchase2 = {false,SPR_GIFT_W2,8,T_Gift,NULL,&s_giftchase3}; +statetype s_giftchase3 = {false,SPR_GIFT_W3,10,T_Gift,NULL,&s_giftchase3s}; +statetype s_giftchase3s = {false,SPR_GIFT_W3,3,NULL,NULL,&s_giftchase4}; +statetype s_giftchase4 = {false,SPR_GIFT_W4,8,T_Gift,NULL,&s_giftchase1}; +statetype s_giftdeathcam = {false,SPR_GIFT_W1,1,NULL,NULL,&s_giftdie1}; +statetype s_giftdie1 = {false,SPR_GIFT_W1,1,NULL,A_DeathScream,&s_giftdie2}; +statetype s_giftdie2 = {false,SPR_GIFT_W1,10,NULL,NULL,&s_giftdie3}; +statetype s_giftdie3 = {false,SPR_GIFT_DIE1,10,NULL,NULL,&s_giftdie4}; +statetype s_giftdie4 = {false,SPR_GIFT_DIE2,10,NULL,NULL,&s_giftdie5}; +statetype s_giftdie5 = {false,SPR_GIFT_DIE3,10,NULL,NULL,&s_giftdie6}; +statetype s_giftdie6 = {false,SPR_GIFT_DEAD,20,NULL,A_StartDeathCam,&s_giftdie6}; +statetype s_giftshoot1 = {false,SPR_GIFT_SHOOT1,30,NULL,NULL,&s_giftshoot2}; +statetype s_giftshoot2 = {false,SPR_GIFT_SHOOT2,10,NULL,T_GiftThrow,&s_giftchase1}; +statetype s_fatstand = {false,SPR_FAT_W1,0,T_Stand,NULL,&s_fatstand}; +statetype s_fatchase1 = {false,SPR_FAT_W1,10,T_Fat,NULL,&s_fatchase1s}; +statetype s_fatchase1s = {false,SPR_FAT_W1,3,NULL,NULL,&s_fatchase2}; +statetype s_fatchase2 = {false,SPR_FAT_W2,8,T_Fat,NULL,&s_fatchase3}; +statetype s_fatchase3 = {false,SPR_FAT_W3,10,T_Fat,NULL,&s_fatchase3s}; +statetype s_fatchase3s = {false,SPR_FAT_W3,3,NULL,NULL,&s_fatchase4}; +statetype s_fatchase4 = {false,SPR_FAT_W4,8,T_Fat,NULL,&s_fatchase1}; +statetype s_fatdeathcam = {false,SPR_FAT_W1,1,NULL,NULL,&s_fatdie1}; +statetype s_fatdie1 = {false,SPR_FAT_W1,1,NULL,A_DeathScream,&s_fatdie2}; +statetype s_fatdie2 = {false,SPR_FAT_W1,10,NULL,NULL,&s_fatdie3}; +statetype s_fatdie3 = {false,SPR_FAT_DIE1,10,NULL,NULL,&s_fatdie4}; +statetype s_fatdie4 = {false,SPR_FAT_DIE2,10,NULL,NULL,&s_fatdie5}; +statetype s_fatdie5 = {false,SPR_FAT_DIE3,10,NULL,NULL,&s_fatdie6}; +statetype s_fatdie6 = {false,SPR_FAT_DEAD,20,NULL,A_StartDeathCam,&s_fatdie6}; +statetype s_fatshoot1 = {false,SPR_FAT_SHOOT1,30,NULL,NULL,&s_fatshoot2}; +statetype s_fatshoot2 = {false,SPR_FAT_SHOOT2,10,NULL,T_GiftThrow,&s_fatshoot3}; +statetype s_fatshoot3 = {false,SPR_FAT_SHOOT3,10,NULL,T_Shoot,&s_fatshoot4}; +statetype s_fatshoot4 = {false,SPR_FAT_SHOOT4,10,NULL,T_Shoot,&s_fatshoot5}; +statetype s_fatshoot5 = {false,SPR_FAT_SHOOT3,10,NULL,T_Shoot,&s_fatshoot6}; +statetype s_fatshoot6 = {false,SPR_FAT_SHOOT4,10,NULL,T_Shoot,&s_fatchase1}; +statetype s_fakestand = {false,SPR_FAKE_W1,0,T_Stand,NULL,&s_fakestand}; +statetype s_fakechase1 = {false,SPR_FAKE_W1,10,T_Fake,NULL,&s_fakechase1s}; +statetype s_fakechase1s = {false,SPR_FAKE_W1,3,NULL,NULL,&s_fakechase2}; +statetype s_fakechase2 = {false,SPR_FAKE_W2,8,T_Fake,NULL,&s_fakechase3}; +statetype s_fakechase3 = {false,SPR_FAKE_W3,10,T_Fake,NULL,&s_fakechase3s}; +statetype s_fakechase3s = {false,SPR_FAKE_W3,3,NULL,NULL,&s_fakechase4}; +statetype s_fakechase4 = {false,SPR_FAKE_W4,8,T_Fake,NULL,&s_fakechase1}; +statetype s_fakedie1 = {false,SPR_FAKE_DIE1,10,NULL,A_DeathScream,&s_fakedie2}; +statetype s_fakedie2 = {false,SPR_FAKE_DIE2,10,NULL,NULL,&s_fakedie3}; +statetype s_fakedie3 = {false,SPR_FAKE_DIE3,10,NULL,NULL,&s_fakedie4}; +statetype s_fakedie4 = {false,SPR_FAKE_DIE4,10,NULL,NULL,&s_fakedie5}; +statetype s_fakedie5 = {false,SPR_FAKE_DIE5,10,NULL,NULL,&s_fakedie6}; +statetype s_fakedie6 = {false,SPR_FAKE_DEAD,0,NULL,NULL,&s_fakedie6}; +statetype s_fakeshoot1 = {false,SPR_FAKE_SHOOT,8,NULL,T_FakeFire,&s_fakeshoot2}; +statetype s_fakeshoot2 = {false,SPR_FAKE_SHOOT,8,NULL,T_FakeFire,&s_fakeshoot3}; +statetype s_fakeshoot3 = {false,SPR_FAKE_SHOOT,8,NULL,T_FakeFire,&s_fakeshoot4}; +statetype s_fakeshoot4 = {false,SPR_FAKE_SHOOT,8,NULL,T_FakeFire,&s_fakeshoot5}; +statetype s_fakeshoot5 = {false,SPR_FAKE_SHOOT,8,NULL,T_FakeFire,&s_fakeshoot6}; +statetype s_fakeshoot6 = {false,SPR_FAKE_SHOOT,8,NULL,T_FakeFire,&s_fakeshoot7}; +statetype s_fakeshoot7 = {false,SPR_FAKE_SHOOT,8,NULL,T_FakeFire,&s_fakeshoot8}; +statetype s_fakeshoot8 = {false,SPR_FAKE_SHOOT,8,NULL,T_FakeFire,&s_fakeshoot9}; +statetype s_fakeshoot9 = {false,SPR_FAKE_SHOOT,8,NULL,NULL,&s_fakechase1}; +statetype s_fire1 = {false,SPR_FIRE1,6,NULL,T_Projectile,&s_fire2}; +statetype s_fire2 = {false,SPR_FIRE2,6,NULL,T_Projectile,&s_fire1}; +statetype s_mechastand = {false,SPR_MECHA_W1,0,T_Stand,NULL,&s_mechastand}; +statetype s_mechachase1 = {false,SPR_MECHA_W1,10,T_Chase,A_MechaSound,&s_mechachase1s}; +statetype s_mechachase1s = {false,SPR_MECHA_W1,6,NULL,NULL,&s_mechachase2}; +statetype s_mechachase2 = {false,SPR_MECHA_W2,8,T_Chase,NULL,&s_mechachase3}; +statetype s_mechachase3 = {false,SPR_MECHA_W3,10,T_Chase,A_MechaSound,&s_mechachase3s}; +statetype s_mechachase3s = {false,SPR_MECHA_W3,6,NULL,NULL,&s_mechachase4}; +statetype s_mechachase4 = {false,SPR_MECHA_W4,8,T_Chase,NULL,&s_mechachase1}; +statetype s_mechadie1 = {false,SPR_MECHA_DIE1,10,NULL,A_DeathScream,&s_mechadie2}; +statetype s_mechadie2 = {false,SPR_MECHA_DIE2,10,NULL,NULL,&s_mechadie3}; +statetype s_mechadie3 = {false,SPR_MECHA_DIE3,10,NULL,A_HitlerMorph,&s_mechadie4}; +statetype s_mechadie4 = {false,SPR_MECHA_DEAD,0,NULL,NULL,&s_mechadie4}; +statetype s_mechashoot1 = {false,SPR_MECHA_SHOOT1,30,NULL,NULL,&s_mechashoot2}; +statetype s_mechashoot2 = {false,SPR_MECHA_SHOOT2,10,NULL,T_Shoot,&s_mechashoot3}; +statetype s_mechashoot3 = {false,SPR_MECHA_SHOOT3,10,NULL,T_Shoot,&s_mechashoot4}; +statetype s_mechashoot4 = {false,SPR_MECHA_SHOOT2,10,NULL,T_Shoot,&s_mechashoot5}; +statetype s_mechashoot5 = {false,SPR_MECHA_SHOOT3,10,NULL,T_Shoot,&s_mechashoot6}; +statetype s_mechashoot6 = {false,SPR_MECHA_SHOOT2,10,NULL,T_Shoot,&s_mechachase1}; +statetype s_hitlerchase1 = {false,SPR_HITLER_W1,6,T_Chase,NULL,&s_hitlerchase1s}; +statetype s_hitlerchase1s = {false,SPR_HITLER_W1,4,NULL,NULL,&s_hitlerchase2}; +statetype s_hitlerchase2 = {false,SPR_HITLER_W2,2,T_Chase,NULL,&s_hitlerchase3}; +statetype s_hitlerchase3 = {false,SPR_HITLER_W3,6,T_Chase,NULL,&s_hitlerchase3s}; +statetype s_hitlerchase3s = {false,SPR_HITLER_W3,4,NULL,NULL,&s_hitlerchase4}; +statetype s_hitlerchase4 = {false,SPR_HITLER_W4,2,T_Chase,NULL,&s_hitlerchase1}; +statetype s_hitlerdeathcam = {false,SPR_HITLER_W1,10,NULL,NULL,&s_hitlerdie1}; +statetype s_hitlerdie1 = {false,SPR_HITLER_W1,1,NULL,A_DeathScream,&s_hitlerdie2}; +statetype s_hitlerdie2 = {false,SPR_HITLER_W1,10,NULL,NULL,&s_hitlerdie3}; +statetype s_hitlerdie3 = {false,SPR_HITLER_DIE1,10,NULL,A_Slurpie,&s_hitlerdie4}; +statetype s_hitlerdie4 = {false,SPR_HITLER_DIE2,10,NULL,NULL,&s_hitlerdie5}; +statetype s_hitlerdie5 = {false,SPR_HITLER_DIE3,10,NULL,NULL,&s_hitlerdie6}; +statetype s_hitlerdie6 = {false,SPR_HITLER_DIE4,10,NULL,NULL,&s_hitlerdie7}; +statetype s_hitlerdie7 = {false,SPR_HITLER_DIE5,10,NULL,NULL,&s_hitlerdie8}; +statetype s_hitlerdie8 = {false,SPR_HITLER_DIE6,10,NULL,NULL,&s_hitlerdie9}; +statetype s_hitlerdie9 = {false,SPR_HITLER_DIE7,10,NULL,NULL,&s_hitlerdie10}; +statetype s_hitlerdie10 = {false,SPR_HITLER_DEAD,20,NULL,A_StartDeathCam,&s_hitlerdie10}; +statetype s_hitlershoot1 = {false,SPR_HITLER_SHOOT1,30,NULL,NULL,&s_hitlershoot2}; +statetype s_hitlershoot2 = {false,SPR_HITLER_SHOOT2,10,NULL,T_Shoot,&s_hitlershoot3}; +statetype s_hitlershoot3 = {false,SPR_HITLER_SHOOT3,10,NULL,T_Shoot,&s_hitlershoot4}; +statetype s_hitlershoot4 = {false,SPR_HITLER_SHOOT2,10,NULL,T_Shoot,&s_hitlershoot5}; +statetype s_hitlershoot5 = {false,SPR_HITLER_SHOOT3,10,NULL,T_Shoot,&s_hitlershoot6}; +statetype s_hitlershoot6 = {false,SPR_HITLER_SHOOT2,10,NULL,T_Shoot,&s_hitlerchase1}; + +void SelectRunDir (objtype *ob) +{ + int deltax,deltay; + dirtype d[3]; + dirtype tdir; + + deltax=player.tilex - ob->tilex; + deltay=player.tiley - ob->tiley; + + if (deltax<0) + d[1]= east; + else + d[1]= west; + if (deltay<0) + d[2]=south; + else + d[2]=north; + + if (abs(deltay)>abs(deltax)) + { + tdir=d[1]; + d[1]=d[2]; + d[2]=tdir; + } + + ob->dir=d[1]; + if (TryWalk(ob)) + return; /*either moved forward or attacked*/ + + ob->dir=d[2]; + if (TryWalk(ob)) + return; + +/* there is no direct path to the player, so pick another direction */ + + if (US_RndT()>128) /*randomly determine direction of search*/ + { + for (tdir=north;tdir<=west;tdir++) + { + ob->dir=tdir; + if ( TryWalk(ob) ) + return; + } + } + else + { + for (tdir=west;tdir>=north;tdir--) + { + ob->dir=tdir; + if ( TryWalk(ob) ) + return; + } + } + + ob->dir = nodir; // can't move +} + +void T_Schabb (objtype *ob) +{ + int32_t move; + int dx,dy,dist; + bool dodge; + + dodge = false; + dx = abs(ob->tilex - player.tilex); + dy = abs(ob->tiley - player.tiley); + dist = dx>dy ? dx : dy; + + if (CheckLine(ob)) // got a shot at player? + { + + if ( US_RndT() < (tics<<3) ) + { + + NewState (ob,&s_schabbshoot1); + return; + } + dodge = true; + } + + if (ob->dir == nodir) + { + if (dodge) + SelectDodgeDir (ob); + else + SelectChaseDir (ob); + if (ob->dir == nodir) + return; // object is blocked in + } + + move = ob->speed*tics; + + while (move) + { + if (ob->distance < 0) + { + + OpenDoor ((unsigned)(-ob->distance-1)); + if (doorobjlist[-ob->distance-1].action != dr_open) + return; + ob->distance = TILEGLOBAL; // go ahead, the door is now opoen + } + + if (move < ob->distance) + { + MoveObj (ob,move); + break; + } + + ob->x = ((int32_t)ob->tilex<y = ((int32_t)ob->tiley<distance; + + if (dist <4) + SelectRunDir (ob); + else if (dodge) + SelectDodgeDir (ob); + else + SelectChaseDir (ob); + + if (ob->dir == nodir) + return; // object is blocked in + } + +} + +void T_Gift (objtype *ob) +{ + int32_t move; + int dx,dy,dist; + bool dodge; + + dodge = false; + dx = abs(ob->tilex - player.tilex); + dy = abs(ob->tiley - player.tiley); + dist = dx>dy ? dx : dy; + + if (CheckLine(ob)) // got a shot at player? + { + + if ( US_RndT() < (tics<<3) ) + { + + NewState (ob,&s_giftshoot1); + return; + } + dodge = true; + } + + if (ob->dir == nodir) + { + if (dodge) + SelectDodgeDir (ob); + else + SelectChaseDir (ob); + if (ob->dir == nodir) + return; // object is blocked in + } + + move = ob->speed*tics; + + while (move) + { + if (ob->distance < 0) + { + + OpenDoor ((unsigned)(-ob->distance-1)); + if (doorobjlist[-ob->distance-1].action != dr_open) + return; + ob->distance = TILEGLOBAL; // go ahead, the door is now opoen + } + + if (move < ob->distance) + { + MoveObj (ob,move); + break; + } + + ob->x = ((int32_t)ob->tilex<y = ((int32_t)ob->tiley<distance; + + if (dist <4) + SelectRunDir (ob); + else if (dodge) + SelectDodgeDir (ob); + else + SelectChaseDir (ob); + + if (ob->dir == nodir) + return; // object is blocked in + } + +} + +void T_Fat (objtype *ob) +{ + int32_t move; + int dx,dy,dist; + bool dodge; + + dodge = false; + dx = abs(ob->tilex - player.tilex); + dy = abs(ob->tiley - player.tiley); + dist = dx>dy ? dx : dy; + + if (CheckLine(ob)) // got a shot at player? + { + + if ( US_RndT() < (tics<<3) ) + { + + NewState (ob,&s_fatshoot1); + return; + } + dodge = true; + } + + if (ob->dir == nodir) + { + if (dodge) + SelectDodgeDir (ob); + else + SelectChaseDir (ob); + if (ob->dir == nodir) + return; // object is blocked in + } + + move = ob->speed*tics; + + while (move) + { + if (ob->distance < 0) + { + + OpenDoor ((unsigned)(-ob->distance-1)); + if (doorobjlist[-ob->distance-1].action != dr_open) + return; + ob->distance = TILEGLOBAL; // go ahead, the door is now opoen + } + + if (move < ob->distance) + { + MoveObj (ob,move); + break; + } + + ob->x = ((int32_t)ob->tilex<y = ((int32_t)ob->tiley<distance; + + if (dist <4) + SelectRunDir (ob); + else if (dodge) + SelectDodgeDir (ob); + else + SelectChaseDir (ob); + + if (ob->dir == nodir) + return; // object is blocked in + } + +} + +void T_Fake (objtype *ob) +{ + int32_t move; + + if (CheckLine(ob)) // got a shot at player? + { + if ( US_RndT() < (tics<<1) ) + { + + NewState (ob,&s_fakeshoot1); + return; + } + } + + if (ob->dir == nodir) + { + SelectDodgeDir (ob); + if (ob->dir == nodir) + return; // object is blocked in + } + + move = ob->speed*tics; + + while (move) + { + if (move < ob->distance) + { + MoveObj (ob,move); + break; + } + + ob->x = ((int32_t)ob->tilex<y = ((int32_t)ob->tiley<distance; + + SelectDodgeDir (ob); + + if (ob->dir == nodir) + return; // object is blocked in + } + +} + +/* Original wall/static sentinel collision, separated from real actors. */ +bool ProjectileTryMove(objtype *ob) +{ + int xl=WL_FloorShift((int64_t)ob->x-PROJSIZE,16),xh=WL_FloorShift((int64_t)ob->x+PROJSIZE,16); + int yl=WL_FloorShift((int64_t)ob->y-PROJSIZE,16),yh=WL_FloorShift((int64_t)ob->y+PROJSIZE,16); + if (xl<0 || yl<0 || xh>=64 || yh>=64) return false; + for (int y=yl;y<=yh;++y) for (int x=xl;x<=xh;++x) { + unsigned tile=tilemap[x][y]; + if (staticblock[x][y] || (tile && tile!=64 && + (!(tile&128) || (tile&64) || DoorSolid(tile&63)))) return false; + } + return true; +} +void T_Projectile(objtype *ob) +{ + int32_t speed=ob->speed*SimulationTics(); + int32_t dx=FixedByFrac(speed,sintable[ob->angle+90]); + int32_t dy=-FixedByFrac(speed,sintable[ob->angle]); + if (dx>0x10000) dx=0x10000; + if (dy>0x10000) dy=0x10000; + ob->x+=dx;ob->y+=dy; + if (!ProjectileTryMove(ob)) { + if (ob->obclass==rocketobj) { GameSound(MISSILEHITSND,ob);ob->state=&s_boom1; } + else ob->state=NULL; + return; + } + if (abs(ob->x-player.x)y-player.y)>3; + if (ob->obclass==needleobj) damage+=20; + else if (ob->obclass==rocketobj) damage+=30; + TakeDamage(damage,ob);ob->state=NULL;return; + } + ob->tilex=ob->x>>16;ob->tiley=ob->y>>16; +} +void T_SchabbThrow (objtype *ob) +{ + int32_t deltax,deltay; + float angle; + int iangle; + + deltax = player.x - ob->x; + deltay = ob->y - player.y; + angle = (float)atan2 ((double)deltay,(double)deltax); + if (angle<0) + angle = (float)(3.14159265358979323846*2+angle); + iangle = (int)(angle/(3.14159265358979323846*2)*ANGLES); + + objtype *spawn=GetNewActor();if (!spawn) return; + spawn->state = &s_needle1; + spawn->ticcount = 1; + + spawn->tilex = ob->tilex; + spawn->tiley = ob->tiley; + spawn->x = ob->x; + spawn->y = ob->y; + spawn->obclass = needleobj; + spawn->dir = nodir; + spawn->angle = iangle%ANGLES; + spawn->speed = 0x2000l; + + spawn->flags = FL_NONMARK; + spawn->active = true; + + GameSound (SCHABBSTHROWSND,spawn); +} + +void T_GiftThrow (objtype *ob) +{ + int32_t deltax,deltay; + float angle; + int iangle; + + deltax = player.x - ob->x; + deltay = ob->y - player.y; + angle = (float)atan2 ((double)deltay,(double)deltax); + if (angle<0) + angle = (float)(3.14159265358979323846*2+angle); + iangle = (int)(angle/(3.14159265358979323846*2)*ANGLES); + + objtype *spawn=GetNewActor();if (!spawn) return; + spawn->state = &s_rocket; + spawn->ticcount = 1; + + spawn->tilex = ob->tilex; + spawn->tiley = ob->tiley; + spawn->x = ob->x; + spawn->y = ob->y; + spawn->obclass = rocketobj; + spawn->dir = nodir; + spawn->angle = iangle%ANGLES; + spawn->speed = 0x2000l; + spawn->flags = FL_NONMARK; + spawn->active = true; + + GameSound (MISSILEFIRESND,spawn); +} + +void T_FakeFire (objtype *ob) +{ + int32_t deltax,deltay; + float angle; + int iangle; + + deltax = player.x - ob->x; + deltay = ob->y - player.y; + angle = (float)atan2 ((double)deltay,(double)deltax); + if (angle<0) + angle = (float)(3.14159265358979323846*2+angle); + iangle = (int)(angle/(3.14159265358979323846*2)*ANGLES); + + objtype *spawn=GetNewActor();if (!spawn) return; + spawn->state = &s_fire1; + spawn->ticcount = 1; + + spawn->tilex = ob->tilex; + spawn->tiley = ob->tiley; + spawn->x = ob->x; + spawn->y = ob->y; + spawn->dir = nodir; + spawn->angle = iangle%ANGLES; + spawn->obclass = fireobj; + spawn->speed = 0x1200l; + spawn->flags = FL_NEVERMARK; + spawn->active = true; + + GameSound (FLAMETHROWERSND,spawn); +} + +void A_Smoke(objtype *ob) +{ + objtype *spawn=GetNewActor();if (!spawn) return; + spawn->state=&s_smoke1;spawn->ticcount=6; + spawn->tilex=ob->tilex;spawn->tiley=ob->tiley; + spawn->x=ob->x;spawn->y=ob->y;spawn->obclass=inertobj; + spawn->active=true;spawn->flags=FL_NEVERMARK; +} +/* Keep the mecha corpse and inherit the original position, reserved move, + direction and flags; SpawnActor consumes the original randomized start tic. */ +void A_HitlerMorph(objtype *ob) +{ + static const int hp[4]={500,700,800,900}; + objtype *spawn=SpawnActor(ob->tilex,ob->tiley,&s_hitlerchase1); + if (!spawn) return; + spawn->speed=SPDPATROL*5;spawn->x=ob->x;spawn->y=ob->y; + spawn->distance=ob->distance;spawn->dir=ob->dir; + spawn->flags=ob->flags|FL_SHOOTABLE; + spawn->obclass=realhitlerobj;spawn->hitpoints=hp[gamestate.difficulty]; +} +void A_MechaSound(objtype *ob) +{ + if (areabyplayer[ob->areanumber]) GameSound(MECHSTEPSND,ob); +} +void A_Slurpie(objtype *ob) { (void)ob;GameSound(SLURPIESND,NULL); } +extern statetype s_bjrun1,s_bjrun1s,s_bjrun2,s_bjrun3,s_bjrun3s,s_bjrun4; +extern statetype s_bjjump1,s_bjjump2,s_bjjump3,s_bjjump4; +bool ValidateBossSprites(void) +{ + static const statetype *const states[]={ + &s_bjrun1,&s_bjrun1s,&s_bjrun2,&s_bjrun3,&s_bjrun3s,&s_bjrun4, + &s_bjjump1,&s_bjjump2,&s_bjjump3,&s_bjjump4, + &s_rocket, + &s_smoke1, + &s_smoke2, + &s_smoke3, + &s_smoke4, + &s_boom1, + &s_boom2, + &s_boom3, + &s_schabbstand, + &s_schabbchase1, + &s_schabbchase1s, + &s_schabbchase2, + &s_schabbchase3, + &s_schabbchase3s, + &s_schabbchase4, + &s_schabbdeathcam, + &s_schabbdie1, + &s_schabbdie2, + &s_schabbdie3, + &s_schabbdie4, + &s_schabbdie5, + &s_schabbdie6, + &s_schabbshoot1, + &s_schabbshoot2, + &s_needle1, + &s_needle2, + &s_needle3, + &s_needle4, + &s_giftstand, + &s_giftchase1, + &s_giftchase1s, + &s_giftchase2, + &s_giftchase3, + &s_giftchase3s, + &s_giftchase4, + &s_giftdeathcam, + &s_giftdie1, + &s_giftdie2, + &s_giftdie3, + &s_giftdie4, + &s_giftdie5, + &s_giftdie6, + &s_giftshoot1, + &s_giftshoot2, + &s_fatstand, + &s_fatchase1, + &s_fatchase1s, + &s_fatchase2, + &s_fatchase3, + &s_fatchase3s, + &s_fatchase4, + &s_fatdeathcam, + &s_fatdie1, + &s_fatdie2, + &s_fatdie3, + &s_fatdie4, + &s_fatdie5, + &s_fatdie6, + &s_fatshoot1, + &s_fatshoot2, + &s_fatshoot3, + &s_fatshoot4, + &s_fatshoot5, + &s_fatshoot6, + &s_fakestand, + &s_fakechase1, + &s_fakechase1s, + &s_fakechase2, + &s_fakechase3, + &s_fakechase3s, + &s_fakechase4, + &s_fakedie1, + &s_fakedie2, + &s_fakedie3, + &s_fakedie4, + &s_fakedie5, + &s_fakedie6, + &s_fakeshoot1, + &s_fakeshoot2, + &s_fakeshoot3, + &s_fakeshoot4, + &s_fakeshoot5, + &s_fakeshoot6, + &s_fakeshoot7, + &s_fakeshoot8, + &s_fakeshoot9, + &s_fire1, + &s_fire2, + &s_mechastand, + &s_mechachase1, + &s_mechachase1s, + &s_mechachase2, + &s_mechachase3, + &s_mechachase3s, + &s_mechachase4, + &s_mechadie1, + &s_mechadie2, + &s_mechadie3, + &s_mechadie4, + &s_mechashoot1, + &s_mechashoot2, + &s_mechashoot3, + &s_mechashoot4, + &s_mechashoot5, + &s_mechashoot6, + &s_hitlerchase1, + &s_hitlerchase1s, + &s_hitlerchase2, + &s_hitlerchase3, + &s_hitlerchase3s, + &s_hitlerchase4, + &s_hitlerdeathcam, + &s_hitlerdie1, + &s_hitlerdie2, + &s_hitlerdie3, + &s_hitlerdie4, + &s_hitlerdie5, + &s_hitlerdie6, + &s_hitlerdie7, + &s_hitlerdie8, + &s_hitlerdie9, + &s_hitlerdie10, + &s_hitlershoot1, + &s_hitlershoot2, + &s_hitlershoot3, + &s_hitlershoot4, + &s_hitlershoot5, + &s_hitlershoot6, + + }; + w3r_byte pixels[4096],mask[4096]; + if (!PM_DecodeSprite(SPR_DEATHCAM,pixels,mask)) return false; + for (unsigned i=0;irotate ? 8U : 1U);++j) + if (!PM_DecodeSprite((unsigned)state->shapenum+j,pixels,mask)) return false; + } + return true; +} diff --git a/src/engine/WL_ACT2.h b/src/engine/WL_ACT2.h new file mode 100644 index 00000000..2d012e88 --- /dev/null +++ b/src/engine/WL_ACT2.h @@ -0,0 +1,150 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_ACT2_H +#define WL_ACT2_H +extern statetype s_rocket; +extern statetype s_smoke1; +extern statetype s_smoke2; +extern statetype s_smoke3; +extern statetype s_smoke4; +extern statetype s_boom1; +extern statetype s_boom2; +extern statetype s_boom3; +extern statetype s_schabbstand; +extern statetype s_schabbchase1; +extern statetype s_schabbchase1s; +extern statetype s_schabbchase2; +extern statetype s_schabbchase3; +extern statetype s_schabbchase3s; +extern statetype s_schabbchase4; +extern statetype s_schabbdeathcam; +extern statetype s_schabbdie1; +extern statetype s_schabbdie2; +extern statetype s_schabbdie3; +extern statetype s_schabbdie4; +extern statetype s_schabbdie5; +extern statetype s_schabbdie6; +extern statetype s_schabbshoot1; +extern statetype s_schabbshoot2; +extern statetype s_needle1; +extern statetype s_needle2; +extern statetype s_needle3; +extern statetype s_needle4; +extern statetype s_giftstand; +extern statetype s_giftchase1; +extern statetype s_giftchase1s; +extern statetype s_giftchase2; +extern statetype s_giftchase3; +extern statetype s_giftchase3s; +extern statetype s_giftchase4; +extern statetype s_giftdeathcam; +extern statetype s_giftdie1; +extern statetype s_giftdie2; +extern statetype s_giftdie3; +extern statetype s_giftdie4; +extern statetype s_giftdie5; +extern statetype s_giftdie6; +extern statetype s_giftshoot1; +extern statetype s_giftshoot2; +extern statetype s_fatstand; +extern statetype s_fatchase1; +extern statetype s_fatchase1s; +extern statetype s_fatchase2; +extern statetype s_fatchase3; +extern statetype s_fatchase3s; +extern statetype s_fatchase4; +extern statetype s_fatdeathcam; +extern statetype s_fatdie1; +extern statetype s_fatdie2; +extern statetype s_fatdie3; +extern statetype s_fatdie4; +extern statetype s_fatdie5; +extern statetype s_fatdie6; +extern statetype s_fatshoot1; +extern statetype s_fatshoot2; +extern statetype s_fatshoot3; +extern statetype s_fatshoot4; +extern statetype s_fatshoot5; +extern statetype s_fatshoot6; +extern statetype s_fakestand; +extern statetype s_fakechase1; +extern statetype s_fakechase1s; +extern statetype s_fakechase2; +extern statetype s_fakechase3; +extern statetype s_fakechase3s; +extern statetype s_fakechase4; +extern statetype s_fakedie1; +extern statetype s_fakedie2; +extern statetype s_fakedie3; +extern statetype s_fakedie4; +extern statetype s_fakedie5; +extern statetype s_fakedie6; +extern statetype s_fakeshoot1; +extern statetype s_fakeshoot2; +extern statetype s_fakeshoot3; +extern statetype s_fakeshoot4; +extern statetype s_fakeshoot5; +extern statetype s_fakeshoot6; +extern statetype s_fakeshoot7; +extern statetype s_fakeshoot8; +extern statetype s_fakeshoot9; +extern statetype s_fire1; +extern statetype s_fire2; +extern statetype s_mechastand; +extern statetype s_mechachase1; +extern statetype s_mechachase1s; +extern statetype s_mechachase2; +extern statetype s_mechachase3; +extern statetype s_mechachase3s; +extern statetype s_mechachase4; +extern statetype s_mechadie1; +extern statetype s_mechadie2; +extern statetype s_mechadie3; +extern statetype s_mechadie4; +extern statetype s_mechashoot1; +extern statetype s_mechashoot2; +extern statetype s_mechashoot3; +extern statetype s_mechashoot4; +extern statetype s_mechashoot5; +extern statetype s_mechashoot6; +extern statetype s_hitlerchase1; +extern statetype s_hitlerchase1s; +extern statetype s_hitlerchase2; +extern statetype s_hitlerchase3; +extern statetype s_hitlerchase3s; +extern statetype s_hitlerchase4; +extern statetype s_hitlerdeathcam; +extern statetype s_hitlerdie1; +extern statetype s_hitlerdie2; +extern statetype s_hitlerdie3; +extern statetype s_hitlerdie4; +extern statetype s_hitlerdie5; +extern statetype s_hitlerdie6; +extern statetype s_hitlerdie7; +extern statetype s_hitlerdie8; +extern statetype s_hitlerdie9; +extern statetype s_hitlerdie10; +extern statetype s_hitlershoot1; +extern statetype s_hitlershoot2; +extern statetype s_hitlershoot3; +extern statetype s_hitlershoot4; +extern statetype s_hitlershoot5; +extern statetype s_hitlershoot6; + +void T_Projectile(objtype *ob); +void A_Smoke(objtype *ob); +void T_Schabb(objtype *ob); +void T_Gift(objtype *ob); +void T_Fat(objtype *ob); +void T_SchabbThrow(objtype *ob); +void T_GiftThrow(objtype *ob); +void T_Fake(objtype *ob); +void T_FakeFire(objtype *ob); +void A_HitlerMorph(objtype *ob); +void A_MechaSound(objtype *ob); +void A_Slurpie(objtype *ob); +void A_StartDeathCam(objtype *ob); +extern statetype s_deathcam; +void SelectRunDir(objtype *ob); +bool ProjectileTryMove(objtype *ob); +bool ValidateBossSprites(void); +#endif diff --git a/src/engine/WL_ACTOR.h b/src/engine/WL_ACTOR.h new file mode 100644 index 00000000..d6951a7c --- /dev/null +++ b/src/engine/WL_ACTOR.h @@ -0,0 +1,111 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_ACTOR_H +#define WL_ACTOR_H +#include "WL_SPRITES.h" +#include "WL_SOUND.h" +#define MAXACTORS 150 +#define MAXSTATS 400 +#define FL_SHOOTABLE 1U +#define FL_VISABLE 8U +#define FL_ATTACKMODE 16U +#define FL_FIRSTATTACK 32U +#define FL_AMBUSH 64U +#define FL_NONMARK 128U +#define FL_NEVERMARK 4U +#define MINACTORDIST INT32_C(65536) +#define TILESHIFT 16 +#define UNSIGNEDSHIFT 8 +#define MINSIGHT INT32_C(0x18000) +#define ICONARROWS 90 +#define RUNSPEED 6000 +#define SPDPATROL 512 +#define SPDDOG 1500 +#define ACTORSIZE INT32_C(0x4000) +typedef enum { east,northeast,north,northwest,west,southwest,south,southeast,nodir } dirtype; +typedef enum { nothing,playerobj,inertobj,guardobj,officerobj,ssobj,dogobj,bossobj,schabbobj,fakeobj,mechahitlerobj,mutantobj,needleobj,fireobj,bjobj,ghostobj,realhitlerobj,gretelobj,giftobj,fatobj,rocketobj,spectreobj,angelobj,transobj,uberobj,willobj,deathobj,hrocketobj,sparkobj } classtype; +typedef enum { dressing,block,bo_gibs,bo_alpo,bo_firstaid,bo_key1,bo_key2,bo_key3,bo_key4,bo_cross,bo_chalice,bo_bible,bo_crown,bo_clip,bo_clip2,bo_machinegun,bo_chaingun,bo_food,bo_fullheal,bo_25clip,bo_spear } stat_t; +typedef enum { wp_knife,wp_pistol,wp_machinegun,wp_chaingun } weapontype; +typedef struct statestruct { + int rotate,shapenum,tictime; + void (*think)(objtype *),(*action)(objtype *); + struct statestruct *next; +} statetype; +typedef struct { int tilex,tiley,shapenum;stat_t itemnumber;bool bonus; } statobj_t; +typedef struct { + int health,ammo,lives,keys,score,nextextra,weapon,bestweapon,chosenweapon; + int attackframe,weaponframe,attackcount,faceframe,killcount,killtotal,treasurecount,treasuretotal; + int episode,mapon,difficulty,oldscore,secretcount,secrettotal; + int32_t killx,killy; + uint32_t TimeCount; + bool died,victoryflag; +} gametype; +extern gametype gamestate; +extern objtype objlist[MAXACTORS],*actorat[64][64]; +extern unsigned objcount,statcount; +extern objtype *killerobj; +bool GameFinished(void); +extern statobj_t statobjlist[MAXSTATS]; +extern bool staticblock[64][64],spotvis[64][64],areabyplayer[37],madenoise; +extern unsigned wallheight[MAXVIEWWIDTH]; +extern int areaMap[64][64],thrustspeed; +void InitObjects(void); +objtype *GetNewActor(void); +objtype *SpawnActor(int x,int y,statetype *state); +void RemoveActor(objtype *ob); +bool ActorAllocationFailed(void); +bool ValidateActorSprites(void); +bool ScanInfoPlane(void); +void ConnectAreas(void); +void DoActor(objtype *ob); +void NewState(objtype *ob,statetype *state); +bool TryWalk(objtype *ob); +void MoveObj(objtype *ob,int32_t move); +void SelectDodgeDir(objtype *ob); +void SelectChaseDir(objtype *ob); +void SelectPathDir(objtype *ob); +bool CheckLine(objtype *ob); +bool CheckSight(objtype *ob); +bool SightPlayer(objtype *ob); +void FirstSighting(objtype *ob); +void DamageActor(objtype *ob,int damage); +void KillActor(objtype *ob); +void T_Stand(objtype *ob); +void T_Path(objtype *ob); +void T_Chase(objtype *ob); +void T_DogChase(objtype *ob); +void T_Ghosts(objtype *ob); +void T_Shoot(objtype *ob); +void T_Bite(objtype *ob); +void A_DeathScream(objtype *ob); +/* Optional synchronous sound sink. NULL actor means a non-positional sound. + The sink must not mutate simulation or retain the actor pointer. */ +void SetGameSoundHook(void (*hook)(soundnames,const objtype *)); +void UpdateSoundLoc(void); +void GameSoundPosition(int32_t gx,int32_t gy,unsigned *left,unsigned *right); +void GameSound(soundnames sound,const objtype *actor); +void PlaceItemType(stat_t item,int x,int y); +void GetBonus(statobj_t *obj); +void GivePoints(int points); +void GiveAmmo(int ammo); +void GiveWeapon(int weapon); +void HealSelf(int points); +void TakeDamage(int points,objtype *attacker); +void CheckWeaponChange(void); +void T_Attack(bool attack); +void UpdateFace(void); +bool DrawStatus(void); +void ResetStatus(void); +void InvalidateStatus(void); +void ClearPaletteShifts(void); +void StartBonusFlash(void); +void StartDamageFlash(int damage); +void FinishPaletteShifts(void); +bool UpdatePaletteShifts(void); +void TransformActor(objtype *ob); +bool TransformTile(int tx,int ty,int *x,int *height); +int CalcRotate(const objtype *ob); +bool DrawScaleds(void); +bool ScaleShape(int xcenter,unsigned shapenum,unsigned height); +bool SimpleScaleShape(int xcenter,unsigned shapenum,unsigned height); +#include "WL_ACT2.h" +#endif diff --git a/src/engine/WL_AGENT.c b/src/engine/WL_AGENT.c new file mode 100644 index 00000000..12facd25 --- /dev/null +++ b/src/engine/WL_AGENT.c @@ -0,0 +1,92 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_AGENT.C TryMove, ClipMove, Thrust and ControlMovement. + Same MINDIST square, axis-slide order and movement/angle constants. */ +#include "WL_DEF.h" +#include "ID_CA.h" +#include "ID_SD.h" +#include +#include +static int anglefrac; +void ResetMovement(void) { anglefrac=0; } +bool TryMove(const objtype *ob) +{ + int xl=WL_FloorShift((int64_t)ob->x-MINDIST,16),xh=WL_FloorShift((int64_t)ob->x+MINDIST,16); + int yl=WL_FloorShift((int64_t)ob->y-MINDIST,16),yh=WL_FloorShift((int64_t)ob->y+MINDIST,16); + if (xl<0 || yl<0 || xh>=64 || yh>=64) return false; + for (int y=yl;y<=yh;++y) for (int x=xl;x<=xh;++x) if (!actorat[x][y] && tilemap[x][y] && tilemap[x][y]!=64) { + unsigned tile=tilemap[x][y]; + if (!(tile&128) || DoorSolid(tile&127)) return false; + } + for (int y=yl;y<=yh;++y) for (int x=xl;x<=xh;++x) if (!actorat[x][y] && staticblock[x][y]) return false; + /* DOS tests the expanded reservation grid, not every physical actor. */ + if(xl>0) --xl; + if(yl>0) --yl; + if(xh<63) ++xh; + if(yh<63) ++yh; + for(int y=yl;y<=yh;++y) for(int x=xl;x<=xh;++x) { + const objtype *other=actorat[x][y]; + if (!other || !(other->flags&FL_SHOOTABLE)) continue; + int64_t dx=(int64_t)ob->x-other->x,dy=(int64_t)ob->y-other->y; + if (dx>=-MINACTORDIST && dx<=MINACTORDIST && dy>=-MINACTORDIST && dy<=MINACTORDIST) return false; + } + return true; +} +void ClipMove(objtype *ob,int32_t dx,int32_t dy) +{ + int32_t x=ob->x,y=ob->y; + /* Internal thrust deltas are bounded; wide checks also protect this API. */ + int64_t nx=(int64_t)x+dx,ny=(int64_t)y+dy; + if (nx<0 || ny<0 || nx>=64*65536 || ny>=64*65536) return; + ob->x=(int32_t)nx; ob->y=(int32_t)ny; if (TryMove(ob)) return; + sd_status audio;SD_GetStatus(&audio); + if(audio.sound<0) GameSound(HITWALLSND,NULL); + ob->y=y; if (TryMove(ob)) return; + ob->x=x; ob->y=(int32_t)ny; if (TryMove(ob)) return; + ob->x=x; ob->y=y; +} +void Thrust(int angle,int32_t speed) +{ + thrustspeed+=speed; + if (speed>=MINDIST*2) speed=MINDIST*2-1; + int32_t dx=FixedByFrac(speed,sintable[angle+90]); + int32_t dy=-FixedByFrac(speed,sintable[angle]); + ClipMove(&player,dx,dy); + player.tilex=player.x/65536; player.tiley=player.y/65536; + if (CA_Map()->planes[1][player.tiley*64+player.tilex]==99) (void)VictoryTile(); +} +void ControlMovement(int controlx,int controly,bool strafe) +{ + if (strafe) { + if (controlx>0) Thrust((player.angle+270)%360,controlx*150); + else if (controlx<0) Thrust((player.angle+90)%360,-controlx*150); + } else { + anglefrac+=controlx; + int units=anglefrac/20; anglefrac-=units*20; + player.angle=(player.angle-units)%360;if(player.angle<0) player.angle+=360; + } + if (controly<0) Thrust(player.angle,-controly*150); + else if (controly>0) Thrust((player.angle+180)%360,controly*100); +} + +int Save_GetAngleFraction(void) { return anglefrac; } +void Save_SetAngleFraction(int fraction) { anglefrac=fraction; } + +/* Modern input shares ClipMove/Thrust's original speed constants and tile + interactions, but combines translation once per tic. Classic stays above. */ +void ModernMovement(int turn,int forward,int strafe,int move) +{ + ControlMovement(turn,0,false); + int f=forward*move*(forward<0?100:150),s=strafe*move*150; + int speed=abs(f)>abs(s)?abs(f):abs(s); + if(f && s) { /* Bound the Euclidean speed to the faster component. */ + int maximum=abs(f)>abs(s)?abs(f):abs(s); + int length=(int)ceil(sqrt((double)f*f+(double)s*s)); + f=(int)((int64_t)f*maximum/length);s=(int)((int64_t)s*maximum/length); + } + int32_t dx=FixedByFrac(f,sintable[player.angle+90])+FixedByFrac(s,sintable[(player.angle+270)%360+90]); + int32_t dy=-FixedByFrac(f,sintable[player.angle])-FixedByFrac(s,sintable[(player.angle+270)%360]); + if(!f && !s) return; + thrustspeed+=speed;ClipMove(&player,dx,dy); + player.tilex=player.x/65536;player.tiley=player.y/65536; + if(CA_Map()->planes[1][player.tiley*64+player.tilex]==99) (void)VictoryTile(); +} diff --git a/src/engine/WL_ASM.c b/src/engine/WL_ASM.c new file mode 100644 index 00000000..0c92cdbf --- /dev/null +++ b/src/engine/WL_ASM.c @@ -0,0 +1,62 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_DRAW.C FixedByFrac asm: the second operand is SIGNED MAGNITUDE, + and only its low 16-bit fraction is multiplied. Explicit 32-bit wrap. */ +#include "WL_DEF.h" +#include +#include +uint32_t sintable[450]; +int32_t finetangent[900]; +int pixelangle[MAXVIEWWIDTH]; +static int32_t FromBits(uint32_t bits) +{ + return bits<=INT32_MAX ? (int32_t)bits : -(int32_t)(UINT32_MAX-bits)-1; +} +int32_t FixedByFrac(int32_t a,uint32_t b) +{ + uint64_t magnitude=a<0 ? (uint64_t)(-(int64_t)a) : (uint64_t)a; + uint32_t product=(uint32_t)((magnitude*(b&UINT32_C(65535)))>>16); + if ((a<0) != ((b&UINT32_C(0x80000000))!=0)) product=0U-product; + return FromBits(product); +} +int32_t WL_FloorShift(int64_t value,unsigned bits) +{ + if (bits>=63) return value<0 ? -1 : 0; + int64_t divisor=INT64_C(1)<INT32_MAX) return INT32_MAX; + return (int32_t)result; +} +void BuildTables(void) +{ + /* Same float stores and half-angle tangent sampling as WL_MAIN.C. */ + const double pi=3.141592657; + const float radtoint=(float)(3600/2/pi); + for (int i=0;i<450;++i) { + double tangent=tan((i+0.5)/radtoint); + finetangent[i]=(int32_t)(tangent*65536); + finetangent[899-i]=(int32_t)(65536/tangent); + } + float angle=0,step=(float)(pi/2/90); + for (int i=0;i<=90;++i) { + uint32_t value=(uint32_t)(65536*sin(angle)); + sintable[i]=sintable[180-i]=value; + if (i+360<450) sintable[i+360]=value; + if (360-i<450) sintable[360-i]=value|UINT32_C(0x80000000); + sintable[180+i]=value|UINT32_C(0x80000000); + angle+=step; + } + CalcProjection(); +} +void CalcProjection(void) +{ + const float radtoint=(float)(3600/2/3.141592657); + double facedist=FOCALLENGTH+MINDIST; + for (int i=0;i +#include +#include +bool WL_AspectFit(unsigned cw,unsigned ch,unsigned aw,unsigned ah,wl_rectangle *o) +{ + if(!o || !cw || !ch || !aw || !ah) return false; + uint64_t w,h; + if((uint64_t)cw*ah <= (uint64_t)ch*aw) { + w=cw;h=(uint64_t)cw*ah/aw; + } else { + h=ch;w=(uint64_t)ch*aw/ah; + } + if(!w || !h || w>UINT_MAX || h>UINT_MAX) return false; + o->width=(unsigned)w;o->height=(unsigned)h; + o->x=(cw-o->width)/2;o->y=(ch-o->height)/2;return true; +} +bool WL_HorizontalFov(double reference,unsigned aw,unsigned ah,double *out) +{ + if(!out || !aw || !ah || !(reference>0.0 && reference<179.0)) return false; + const double pi=3.14159265358979323846; + const double radians=reference*pi/180.0; + const double ratio=((double)aw/(double)ah)/(4.0/3.0); + double fov=2.0*atan(tan(radians/2.0)*ratio)*180.0/pi; + if(!(fov>0.0 && fov<180.0)) return false; + *out=fov;return true; +} + +bool WL_AutoRenderSize(unsigned display_w,unsigned display_h,unsigned *width,unsigned *height) +{ + if(!width || !height || display_w<320 || display_h<200) return false; + unsigned cap_w=display_w<1920U?display_w:1920U; + unsigned cap_h=display_h<1080U?display_h:1080U; + wl_rectangle fit; + if(!WL_AspectFit(cap_w,cap_h,display_w,display_h,&fit) || + fit.width<320U || fit.height<200U) return false; + *width=fit.width;*height=fit.height; + return true; +} diff --git a/src/engine/WL_ASPECT.h b/src/engine/WL_ASPECT.h new file mode 100644 index 00000000..4b0d6673 --- /dev/null +++ b/src/engine/WL_ASPECT.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_ASPECT_H +#define WL_ASPECT_H +#include +/* Pure geometry helpers for a future high-resolution renderer. + No simulation state, renderer ownership or game-data dependencies. */ +typedef struct { unsigned x,y,width,height; } wl_rectangle; +/* Preserve source display aspect in a destination canvas, using integer + arithmetic. Width/height are physical/display pixel units. */ +bool WL_AspectFit(unsigned canvas_w,unsigned canvas_h, + unsigned aspect_w,unsigned aspect_h,wl_rectangle *out); +/* Auto internal software-render resolution: never exceed the display size + or 1920x1080, preserving the display aspect. The actual window is scaled + separately by SDL, so a 4K output does not imply 4K CPU raycasting. */ +bool WL_AutoRenderSize(unsigned display_w,unsigned display_h,unsigned *width,unsigned *height); +/* Horizontal camera FOV for aspect ratios when vertical framing is fixed. + Takes the horizontal FOV of a 4:3 reference in degrees. */ +bool WL_HorizontalFov(double original_fov_deg, + unsigned aspect_w,unsigned aspect_h,double *out); +#endif diff --git a/src/engine/WL_COMBAT.c b/src/engine/WL_COMBAT.c new file mode 100644 index 00000000..2835bbe7 --- /dev/null +++ b/src/engine/WL_COMBAT.c @@ -0,0 +1,234 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_AGENT.C inventory, attackinfo, T_Attack and status-bar drawing. No gameplay assets. */ +#include "WL_DEF.h" +#include "WL_DEMO.h" +#include "WL_MAIN.h" +#include "WL_SAVE.h" +#include "WL_CONTROLS.h" +#include "ID_CA.h" +#include "ID_IN.h" +#include "ID_VH.h" +#include "ID_US_1.h" +#include +#include +#include +objtype *killerobj; +static objtype killersnapshot; +static int facecount; +static bool attackheld,gotgatgun,lastgatgun; +static gametype laststatus; +static bool statusvalid; +void ResetStatus(void) { ClearPaletteShifts();facecount=0;killerobj=NULL;attackheld=gotgatgun=false;statusvalid=false; } +void HealSelf(int points) { gotgatgun=false;gamestate.health+=points;if (gamestate.health>100) gamestate.health=100; } +void GiveAmmo(int ammo) +{ + if (!gamestate.ammo && !gamestate.attackframe) gamestate.weapon=gamestate.chosenweapon; + gamestate.ammo+=ammo;if (gamestate.ammo>99) gamestate.ammo=99; +} +static void GiveExtraMan(void) { GameSound(BONUS1UPSND,NULL); if (gamestate.lives<9) ++gamestate.lives; } +void GivePoints(int points) +{ + gamestate.score+=points; + while (gamestate.score>=gamestate.nextextra) { gamestate.nextextra+=40000;GiveExtraMan(); } +} +void GiveWeapon(int weapon) +{ + GiveAmmo(6); + if (gamestate.bestweaponitemnumber) { + case bo_firstaid: if (gamestate.health==100) return;HealSelf(25);GameSound(HEALTH2SND,NULL);break; + case bo_key1: case bo_key2: case bo_key3: case bo_key4: GameSound(GETKEYSND,NULL);gamestate.keys|=1<<(ob->itemnumber-bo_key1);break; + case bo_cross: GivePoints(100);++gamestate.treasurecount;GameSound(BONUS1SND,NULL);break; + case bo_chalice: GivePoints(500);++gamestate.treasurecount;GameSound(BONUS2SND,NULL);break; + case bo_bible: GivePoints(1000);++gamestate.treasurecount;GameSound(BONUS3SND,NULL);break; + case bo_crown: GivePoints(5000);++gamestate.treasurecount;GameSound(BONUS4SND,NULL);break; + case bo_clip: case bo_clip2: if (gamestate.ammo==99) return;GiveAmmo(ob->itemnumber==bo_clip?8:4);GameSound(GETAMMOSND,NULL);break; + case bo_machinegun: GiveWeapon(wp_machinegun);GameSound(GETMACHINESND,NULL);break; + case bo_chaingun: GiveWeapon(wp_chaingun);gotgatgun=true;facecount=0;GameSound(GETGATLINGSND,NULL);break; + case bo_fullheal: HealSelf(99);GiveAmmo(25);GiveExtraMan();++gamestate.treasurecount;break; + case bo_food: if (gamestate.health==100) return;HealSelf(10);GameSound(HEALTH1SND,NULL);break; + case bo_alpo: if (gamestate.health==100) return;HealSelf(4);GameSound(HEALTH1SND,NULL);break; + case bo_gibs: if (gamestate.health>10) return;HealSelf(1);GameSound(SLURPIESND,NULL);break; + default: return; + } + StartBonusFlash(); + ob->shapenum=-1; +} +void UpdateFace(void) +{ + facecount+=SimulationTics(); + if (facecount>US_RndT()) { + gamestate.faceframe=US_RndT()>>6; + if (gamestate.faceframe==3) gamestate.faceframe=1; + facecount=0;gotgatgun=false; + } +} +static bool StatusDrawPic(int x,int y,int pic) { return VWB_DrawPic(x*8,160+y,pic); } +static bool LatchNumber(int x,int y,unsigned width,int number) +{ + char text[24];int n=snprintf(text,sizeof(text),"%d",number); + if (n<0 || (size_t)n>=sizeof(text)) return CA_Fail("Status number overflow"); + unsigned length=(unsigned)n; + while (length=0 && !StatusDrawPic(32,8,KNIFEPIC+gamestate.weapon)) || + !StatusDrawPic(30,4,(gamestate.keys&1)?GOLDKEYPIC:NOKEYPIC) || + !StatusDrawPic(30,20,(gamestate.keys&2)?SILVERKEYPIC:NOKEYPIC) || + !StatusDrawPic(17,4,gotgatgun ? GOTGATLINGPIC : gamestate.health ? FACE1APIC+3*((100-gamestate.health)/16)+gamestate.faceframe : FACE8APIC)) return false; + laststatus=gamestate;lastgatgun=gotgatgun;statusvalid=true;return true; +} +void KnifeAttack (objtype *ob) +{ + objtype *check,*closest; + int32_t dist; + GameSound(ATKKNIFESND,NULL); + + dist = 0x7fffffff; + closest = NULL; + for (check=ob->next ; check ; check=check->next) + if ( (check->flags & FL_SHOOTABLE) + && (check->flags & FL_VISABLE) + && abs (check->viewx-(VIEWWIDTH/2-1)) < (VIEWWIDTH/10) + ) + { + if (check->transx < dist) + { + dist = check->transx; + closest = check; + } + } + if (!closest || dist> 0x18000l) + { + return; + } + DamageActor (closest,US_RndT() >> 4); +} +void GunAttack (objtype *ob) +{ + objtype *check,*closest,*oldclosest; + int damage; + int dx,dy,dist; + int32_t viewdist; + GameSound(gamestate.weapon==wp_pistol?ATKPISTOLSND:gamestate.weapon==wp_machinegun?ATKMACHINEGUNSND:ATKGATLINGSND,NULL); + madenoise = true; + viewdist = 0x7fffffffl; + closest = NULL; + while (1) + { + oldclosest = closest; + for (check=ob->next ; check ; check=check->next) + if ( (check->flags & FL_SHOOTABLE) + && (check->flags & FL_VISABLE) + && abs (check->viewx-(VIEWWIDTH/2-1)) < (VIEWWIDTH/10) + ) + { + if (check->transx < viewdist) + { + viewdist = check->transx; + closest = check; + } + } + if (closest == oldclosest) + return; + if (CheckLine(closest)) + break; + } + dx = abs(closest->tilex - player.tilex); + dy = abs(closest->tiley - player.tiley); + dist = dx>dy ? dx:dy; + if (dist<2) + damage = US_RndT() / 4; + else if (dist<4) + damage = US_RndT() / 6; + else + { + if ( (US_RndT() / 12) < dist) + return; + damage = US_RndT() / 6; + } + DamageActor (closest,damage); +} +struct atkinf { int tics,attack,frame; }; +static const struct atkinf attackinfo[4][4]={ + {{6,0,1},{6,2,2},{6,0,3},{6,-1,4}}, + {{6,0,1},{6,1,2},{6,0,3},{6,-1,4}}, + {{6,0,1},{6,1,2},{6,3,3},{6,-1,4}}, + {{6,0,1},{6,1,2},{6,4,3},{6,-1,4}} +}; +/* WL_AGENT.C CheckWeaponChange: first ready key wins; empty ammunition + preserves the chosen gun so GiveAmmo can restore it from the knife. */ +void CheckWeaponChange(void) +{ + if (!gamestate.ammo) return; + for (int weapon=wp_knife;weapon<=gamestate.bestweapon;++weapon) { + if (Demo_Active()?(Demo_Buttons()&(16U<<(unsigned)weapon))!=0:CT_Down((ct_action)(CT_WEAPON1+weapon))) { + gamestate.weapon=gamestate.chosenweapon=weapon;return; + } + } +} +void T_Attack(bool attack) +{ + if (!gamestate.attackframe) { + CheckWeaponChange(); + if (attack && !attackheld) { + gamestate.attackframe=1;gamestate.attackcount=6;gamestate.weaponframe=1; + } + attackheld=attack;return; + } + /* DOS T_Attack clears a fresh press during an existing attack. The + cleared state becomes next frame's buttonheld, even on the end frame. */ + if (attack && !attackheld) { attack=false;Demo_SuppressButtons(1U); } + attackheld=attack; + gamestate.attackcount-=SimulationTics(); + while(gamestate.attackcount<=0) { + /* attackframe is stored +1 so zero remains the original non-attack state. */ + const struct atkinf *cur=&attackinfo[gamestate.weapon][gamestate.attackframe-1]; + switch (cur->attack) { + case -1: + gamestate.weapon=gamestate.ammo ? gamestate.chosenweapon : wp_knife; + gamestate.attackframe=gamestate.weaponframe=0;return; + case 4: + if (!gamestate.ammo) break; + if (attack) gamestate.attackframe-=2; + /* fall through */ + case 1: + if (!gamestate.ammo) { ++gamestate.attackframe;break; } + GunAttack(&player);--gamestate.ammo;break; + case 2: KnifeAttack(&player);break; + case 3: if (gamestate.ammo && attack) gamestate.attackframe-=2;break; + default: break; + } + gamestate.attackcount+=cur->tics;++gamestate.attackframe; + gamestate.weaponframe=attackinfo[gamestate.weapon][gamestate.attackframe-1].frame; + } +} + +void Save_GetCombat(save_controls *c) { c->facecount=facecount;c->attackheld=attackheld;c->gotgatgun=gotgatgun; } +void Save_SetCombat(const save_controls *c) +{ + facecount=c->facecount;attackheld=c->attackheld;gotgatgun=c->gotgatgun; + statusvalid=false;killerobj=NULL; +} + +void InvalidateStatus(void) { statusvalid=false; } diff --git a/src/engine/WL_CONTROLS.c b/src/engine/WL_CONTROLS.c new file mode 100644 index 00000000..ba77af4a --- /dev/null +++ b/src/engine/WL_CONTROLS.c @@ -0,0 +1,156 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "WL_CONTROLS.h" +#include +#include +static ct_preset preset; +static ct_profile profiles[2]; +static bool initialized[2]; +static bool gameplay; +void CT_SetGameplay(bool active) { gameplay=active; } +bool CT_Gameplay(void) { return gameplay; } +static unsigned bindings[CT_ACTIONS][2]={ + {82,96},{81,90},{80,92},{79,94},{0,0},{0,0},{225,229},{226,230}, + {224,228},{44,0},{30,0},{31,0},{32,0},{33,0},{41,0} +}; +static bool keys[CT_KEYS],pressed[CT_KEYS],buttons[4],clicks[4],mouse,invert; +static unsigned sensitivity=10,nextkey; +static double motion; +void CT_Clear(void) { memset(keys,0,sizeof(keys));memset(buttons,0,sizeof(buttons));motion=0;CT_EndTic(); } +void CT_EndTic(void) { memset(pressed,0,sizeof(pressed));memset(clicks,0,sizeof(clicks));nextkey=0; } +void CT_DefaultProfile(ct_preset value,ct_profile *profile) +{ + static const unsigned classic[CT_ACTIONS][2]={ + {82,96},{81,90},{80,92},{79,94},{0,0},{0,0},{225,229},{226,230}, + {224,228},{44,0},{30,0},{31,0},{32,0},{33,0},{41,0} + }; + memset(profile,0,sizeof(*profile));memcpy(profile->binding,classic,sizeof(classic)); + profile->mouse=value==CT_MODERN;profile->sensitivity=10; + if(value==CT_MODERN) { + profile->binding[CT_FORWARD][0]=26;profile->binding[CT_FORWARD][1]=82; + profile->binding[CT_BACK][0]=22;profile->binding[CT_BACK][1]=81; + profile->binding[CT_STRAFE_LEFT][0]=4;profile->binding[CT_STRAFE_RIGHT][0]=7; + } +} +static bool ValidKey(unsigned action,unsigned key) +{ + return key=4) && + !(key==41 && action!=CT_MENU) && !(key>=58 && key<=69); +} +bool CT_ValidProfile(const ct_profile *profile) +{ + if(!profile || profile->sensitivity<1 || profile->sensitivity>40) return false; + bool used[CT_KEYS]={false}; + for(unsigned a=0;abinding[a][slot]; + if(!ValidKey(a,key) || (key && used[key])) return false; + if(key) used[key]=true; + } + return true; +} +void CT_GetProfile(ct_preset value,ct_profile *profile) +{ + if(value==preset) { + memset(profile,0,sizeof(*profile));memcpy(profile->binding,bindings,sizeof(bindings)); + profile->mouse=mouse;profile->invert=invert;profile->sensitivity=sensitivity; + } else if((unsigned)value<2 && initialized[value]) *profile=profiles[value]; + else CT_DefaultProfile(value,profile); +} +bool CT_SetProfile(ct_preset value,const ct_profile *profile) +{ + if((unsigned)value>=2 || !CT_ValidProfile(profile)) return false; + profiles[value]=*profile;initialized[value]=true; + if(value==preset) { + memcpy(bindings,profile->binding,sizeof(bindings));mouse=profile->mouse; + invert=profile->invert;sensitivity=profile->sensitivity;CT_Clear(); + } + return true; +} +void CT_SelectPreset(ct_preset value) +{ + if((unsigned)value>=2 || value==preset) return; + CT_GetProfile(preset,&profiles[preset]);initialized[preset]=true; + ct_profile next;CT_GetProfile(value,&next);preset=value;(void)CT_SetProfile(value,&next); +} +void CT_Reset(ct_preset value) +{ + if((unsigned)value>=2) return; + if(value!=preset) { CT_GetProfile(preset,&profiles[preset]);initialized[preset]=true; } + ct_profile defaults;CT_DefaultProfile(value,&defaults);preset=value;(void)CT_SetProfile(value,&defaults); +} +ct_preset CT_Preset(void) { return preset; } +void CT_Key(unsigned key,bool down) +{ + if(!key || key>=CT_KEYS) return; + if(down && !keys[key]) { pressed[key]=true;nextkey=key; } + keys[key]=down; +} +void CT_LegacyKey(unsigned scan,bool down) +{ + /* Legacy engine/test callers use original set-1 keys. SDL feeds the USB + keys directly and updates menu state through IN_MenuKeyEvent instead. */ + static const unsigned letters[26]={0x1e,0x30,0x2e,0x20,0x12,0x21,0x22,0x23,0x17,0x24,0x25,0x26,0x32,0x31,0x18,0x19,0x10,0x13,0x1f,0x14,0x16,0x2f,0x11,0x2d,0x15,0x2c}; + for(unsigned i=0;i<26;++i) if(scan==letters[i]) { CT_Key(i+4,down);return; } + if(scan>=2 && scan<=10) { CT_Key(scan+28,down);return; } + unsigned key=0; + switch(scan) { + case 11:key=39;break;case 1:key=41;break;case 0x1c:key=40;break;case 0x39:key=44;break; + case 0x48:key=82;break;case 0x50:key=81;break;case 0x4b:key=80;break;case 0x4d:key=79;break; + case 0x2a:key=225;break;case 0x36:key=229;break;case 0x1d:key=224;break;case 0x38:key=226;break; + default:break; + } + CT_Key(key,down); +} +void CT_MouseButton(unsigned button,bool down) +{ + if(!mouse || button>=4 || !button) return; + if(down && !buttons[button]) clicks[button]=true; + buttons[button]=down; +} +void CT_MouseMotion(double x) +{ + if(!mouse || !(x>=-DBL_MAX && x<=DBL_MAX)) return; + if(x>4096) x=4096; + if(x< -4096) x=-4096; + motion+=x*(double)sensitivity*(invert?-1.0:1.0); + if(motion>7200) motion=7200; + if(motion< -7200) motion=-7200; +} +int CT_MouseTurn(void) { int value=(int)motion;motion-=value;return value; } +bool CT_Down(ct_action action) +{ + if((unsigned)action>=CT_ACTIONS) return false; + for(unsigned slot=0;slot<2;++slot) { unsigned key=bindings[action][slot];if(key && (keys[key] || pressed[key])) return true; } + unsigned button=action==CT_FIRE?1U:action==CT_USE?3U:0U; + return mouse && button && (buttons[button] || clicks[button]); +} +bool CT_Pressed(ct_action action) +{ + if((unsigned)action>=CT_ACTIONS) return false; + bool result=false; + for(unsigned slot=0;slot<2;++slot) { unsigned key=bindings[action][slot];if(key && pressed[key]) { result=true;pressed[key]=false; } } + unsigned button=action==CT_USE?3U:action==CT_FIRE?1U:0U; + if(mouse && button && clicks[button]) { result=true;clicks[button]=false; } + return result; +} +unsigned CT_Binding(ct_action action,unsigned slot) { return (unsigned)action=CT_ACTIONS || slot>=2 || !ValidKey((unsigned)action,key)) return false; + /* Escape remains a safe menu/cancel key; F1-F10 are DOS panel shortcuts; F11 controls scaling and F12 captures screenshots. */ + if((key==41 && action!=CT_MENU) || (key>=58 && key<=69)) return false; + if(key) for(unsigned a=0;a=1 && value<=40) { sensitivity=value;motion=0; } } +bool CT_Invert(void) { return invert; } +void CT_SetInvert(bool value) { invert=value;motion=0; } +unsigned CT_NextKey(void) { unsigned key=nextkey;nextkey=0;return key; } diff --git a/src/engine/WL_CONTROLS.h b/src/engine/WL_CONTROLS.h new file mode 100644 index 00000000..066f600b --- /dev/null +++ b/src/engine/WL_CONTROLS.h @@ -0,0 +1,46 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_CONTROLS_H +#define WL_CONTROLS_H +#include +/* USB physical-key identifiers, matching SDL3 scancodes without an SDL + dependency in the simulation. Zero is unbound. Menu keys stay in ID_IN. */ +#define CT_KEYS 512U +typedef enum { CT_CLASSIC,CT_MODERN } ct_preset; +typedef enum { CT_FORWARD,CT_BACK,CT_LEFT,CT_RIGHT,CT_STRAFE_LEFT,CT_STRAFE_RIGHT, + CT_RUN,CT_ALT,CT_FIRE,CT_USE,CT_WEAPON1,CT_WEAPON2,CT_WEAPON3,CT_WEAPON4,CT_MENU,CT_ACTIONS } ct_action; +typedef struct { + unsigned binding[CT_ACTIONS][2]; + bool mouse,invert; + unsigned sensitivity; +} ct_profile; +void CT_DefaultProfile(ct_preset preset,ct_profile *profile); +void CT_GetProfile(ct_preset preset,ct_profile *profile); +bool CT_SetProfile(ct_preset preset,const ct_profile *profile); +bool CT_ValidProfile(const ct_profile *profile); +void CT_SelectPreset(ct_preset preset); /* Retains each preset's custom profile. */ +void CT_Reset(ct_preset preset); /* Explicit reset to defaults for this preset. */ +void CT_SetGameplay(bool active); +bool CT_Gameplay(void); +ct_preset CT_Preset(void); +void CT_Key(unsigned key,bool down); +void CT_LegacyKey(unsigned scan,bool down); +void CT_MouseButton(unsigned button,bool down); +void CT_MouseMotion(double x); +void CT_Clear(void); +void CT_EndTic(void); +bool CT_Down(ct_action action); +bool CT_Pressed(ct_action action); +int CT_MouseTurn(void); +unsigned CT_Binding(ct_action action,unsigned alternative); +/* Reject duplicate assignments atomically. action/slot/zero are validated. */ +bool CT_Bind(ct_action action,unsigned alternative,unsigned key); +const char *CT_ActionName(ct_action action); +bool CT_MouseEnabled(void); +void CT_SetMouse(bool enabled); +unsigned CT_Sensitivity(void); +void CT_SetSensitivity(unsigned sensitivity); +bool CT_Invert(void); +void CT_SetInvert(bool invert); +/* Binding capture consumes physical keys without changing menu navigation. */ +unsigned CT_NextKey(void); +#endif diff --git a/src/engine/WL_CONTROLS_MENU.c b/src/engine/WL_CONTROLS_MENU.c new file mode 100644 index 00000000..0ddd27d9 --- /dev/null +++ b/src/engine/WL_CONTROLS_MENU.c @@ -0,0 +1,181 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "WL_CONTROLS.h" +#include "WL_MENU.h" +#include "WL_DISPLAY.h" +#include "ID_IN.h" +#include "ID_VH.h" +#include "ID_CA.h" +#include "ID_US_1.h" +#include "ID_SD.h" +#include +static unsigned row,binding,alternative,control_row; +static enum { CONTROL_ROOT,CONTROL_OPTIONS,CONTROL_SENSITIVITY } page; +static bool bindings_page,waiting,conflict; +static const char *KeyName(unsigned key,char text[24]) +{ + if(!key) return "-"; + if(key>=4 && key<=29) { text[0]=(char)('A'+key-4);text[1]=0;return text; } + if(key>=30 && key<=38) { text[0]=(char)('1'+key-30);text[1]=0;return text; } + if(key>=58 && key<=69) { (void)snprintf(text,24,"F%u",key-57);return text; } + if(key>=89 && key<=97) { (void)snprintf(text,24,"KP %u",key-88);return text; } + switch(key) { + case 39:return "0";case 40:return "Enter";case 41:return "Esc";case 42:return "Backspace"; + case 43:return "Tab";case 44:return "Space";case 79:return "Right";case 80:return "Left"; + case 57:return "Caps Lock";case 73:return "Insert";case 74:return "Home";case 75:return "Page Up"; + case 76:return "Delete";case 77:return "End";case 78:return "Page Down";case 98:return "KP 0"; + case 81:return "Down";case 82:return "Up";case 224:return "L Ctrl";case 225:return "L Shift"; + case 226:return "L Alt";case 228:return "R Ctrl";case 229:return "R Shift";case 230:return "R Alt"; + default:(void)snprintf(text,24,"Key %u",key);return text; + } +} +static bool Text(int x,int y,const char *text) { PrintX=x;PrintY=y;return US_Print(text); } +static bool DrawOptions(void) +{ + ClearMScreen();DrawStripes(10);DrawWindow(20,50,280,124,BKGDCOLOR); + fontnumber=1;fontcolor=TEXTCOLOR; + if(!VWB_DrawPic(80,0,C_CUSTOMIZEPIC)) return false; + fontnumber=0; + if(bindings_page) { + if(!Text(30,53,"Action") || !Text(171,53,"Key 1") || !Text(234,53,"Key 2")) return false; + unsigned first=(binding/5)*5; + for(unsigned i=first;i0; + bool left=IN_ConsumePress(sc_LeftArrow),right=IN_ConsumePress(sc_RightArrow); + bool enter=IN_ConsumePress(sc_Enter); + if(up || down) { MenuCursorMoved();(void)SD_PlaySound(MOVEGUN1SND,0,0); } + if(bindings_page) { + if(up || down) binding=(binding+(up?CT_ACTIONS-1U:1U))%CT_ACTIONS; + if(left || right) alternative^=1U; + if(IN_ConsumePress(0x53)) { (void)CT_Bind((ct_action)binding,alternative,0);return Draw()?0:-3; } + if(enter) { waiting=true;conflict=false;IN_ClearKeysDown(); } + return !(up || down || left || right || enter) || Draw()?0:-3; + } + if(up || down) row=(row+(up?(Display_Available()?6U:5U):1U))%(Display_Available()?7U:6U); + if(left || right || enter) { + if(row==0) CT_SelectPreset(CT_Preset()==CT_CLASSIC?CT_MODERN:CT_CLASSIC); + else if(row==1) CT_SetMouse(!CT_MouseEnabled()); + else if(row==2) { + unsigned sensitivity=CT_Sensitivity(); + if(left && sensitivity>1) --sensitivity; + if((right || enter) && sensitivity<40) ++sensitivity; + CT_SetSensitivity(sensitivity); + } else if(row==3) CT_SetInvert(!CT_Invert()); + else if(row==4 && enter) CT_Reset(CT_Preset()); + else if(row==6 && enter) return 2; + else if(row==5 && enter) { bindings_page=true;binding=alternative=0; } + if(enter) (void)SD_PlaySound(SHOOTSND,0,0); + IN_ClearKeysDown(); + } + return !(up || down || left || right || enter) || Draw()?0:-3; +} + +int HandleControlsMenu(void) +{ + if(page==CONTROL_OPTIONS) { + int action=HandleOptions(); + if(action==-1) { page=CONTROL_ROOT;IN_ClearKeysDown();return Draw()?0:-3; } + return action; + } + if(IN_ConsumePress(sc_Escape)) { + (void)SD_PlaySound(ESCPRESSEDSND,0,0); + if(page==CONTROL_ROOT) return -1; + page=CONTROL_ROOT;IN_ClearKeysDown();return Draw()?0:-3; + } + int direction=MenuNavigation();bool up=direction<0,down=direction>0; + bool left=IN_ConsumePress(sc_LeftArrow),right=IN_ConsumePress(sc_RightArrow); + bool enter=IN_ConsumePress(sc_Enter)|IN_ConsumePress(sc_Space); + if(enter) (void)SD_PlaySound(SHOOTSND,0,0); + if(up || down) { MenuCursorMoved();(void)SD_PlaySound(MOVEGUN1SND,0,0); } + if(page==CONTROL_SENSITIVITY) { + unsigned value=CT_Sensitivity(); + if((left || down) && value>1) --value; + if((right || up) && value<40) ++value; + CT_SetSensitivity(value); + if(enter) page=CONTROL_ROOT; + } else { + if(up || down) do { control_row=(control_row+(up?6U:1U))%7; } while(!ControlActive(control_row)); + if(left || right || enter) { + if(control_row==0) CT_SetMouse(!CT_MouseEnabled()); + else if(control_row==4 && enter) page=CONTROL_SENSITIVITY; + else if(control_row==5 && enter) { page=CONTROL_OPTIONS;row=0; } + else if(control_row==6 && enter && Display_Available()) return 2; + } + } + return !(up || down || left || right || enter) || Draw()?0:-3; +} diff --git a/src/engine/WL_DEF.h b/src/engine/WL_DEF.h new file mode 100644 index 00000000..809bde8a --- /dev/null +++ b/src/engine/WL_DEF.h @@ -0,0 +1,115 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Active normal-level gameplay port of WOLFSRC/WL_DEF.H. */ +#ifndef WL_DEF_H +#define WL_DEF_H +#include "ID_MAP.h" +#define TILEGLOBAL INT32_C(65536) +#define MINDIST INT32_C(0x5800) +#define FOCALLENGTH INT32_C(0x5700) +#define ANGLES 360 +#define FINEANGLES 3600 +#define MAXTICS 10 +#define MAXVIEWWIDTH 304 +extern uint16_t viewwidth,viewheight,viewxorigin,viewyorigin; +#define VIEWWIDTH viewwidth +#define VIEWHEIGHT viewheight +#define VIEWX viewxorigin +#define VIEWY viewyorigin +bool NewViewSize(unsigned size); +unsigned ViewSize(void); +bool BeginViewMenu(void); +int HandleViewMenu(uint64_t ticks); +int SimulationTics(void); /* Normal play: 1. Original demo frames: 4. */ +typedef struct objstruct { + int32_t x,y; int angle,tilex,tiley; + int dir,obclass,areanumber,hitpoints,ticcount,temp1,temp2,viewx,viewheight; + int32_t speed,distance,transx,transy; + unsigned flags; + bool active; + struct statestruct *state; + struct objstruct *next; +} objtype; +typedef enum { dr_closed,dr_opening,dr_open,dr_closing } dooraction; +typedef struct { unsigned x,y,lock; bool vertical; dooraction action; uint16_t position; unsigned ticcount; } doorobj_t; +extern objtype player; +extern w3r_byte tilemap[64][64]; /* Original x-major runtime indexing. */ +extern doorobj_t doorobjlist[64]; +extern unsigned doornum; +extern uint32_t sintable[450]; +extern int32_t finetangent[900]; +extern int pixelangle[MAXVIEWWIDTH]; +int32_t FixedByFrac(int32_t a,uint32_t signed_magnitude); +int32_t WL_FloorShift(int64_t value,unsigned bits); +void BuildTables(void); +void CalcProjection(void); +bool SetupGameLevel(void); +void ShutdownGameLevel(void); +bool TryMove(const objtype *ob); +void ClipMove(objtype *ob,int32_t xmove,int32_t ymove); +void Thrust(int angle,int32_t speed); +void ModernMovement(int turn,int forward,int strafe,int move); +void ControlMovement(int controlx,int controly,bool strafe); +void ResetMovement(void); +void OpenDoor(unsigned door); +void CloseDoor(unsigned door); +void OperateDoor(unsigned door); +void MoveDoors(void); +void Cmd_Use(void); +extern unsigned pwallstate,pwallpos; +extern int pwallx,pwally,pwalldir; +extern bool pushable[64][64]; +void PushWall(int x,int y,int dir); +void MovePWalls(void); +void ResetPushwalls(void); +bool DoorSolid(unsigned door); +/* Original difficulty order: baby, easy, medium, hard. */ +bool NewGame(unsigned difficulty,unsigned episode); +bool GameStartMap(uint64_t ticks,unsigned map,unsigned difficulty,unsigned seed); +bool GameStartSelected(uint64_t ticks,unsigned episode,unsigned difficulty); +bool GameStart(uint64_t ticks); +bool GameWarp(uint64_t ticks,unsigned floor); +typedef enum { ex_playing,ex_completed,ex_secretlevel,ex_victorious } exit_t; +extern exit_t playstate; +bool GameIntermission(void); +bool GamePreloadPending(void); +void GamePreloadConsumed(void); +bool GameLoading(void); +/* DOS artwork ends while black; gameplay fade-in still blocks simulation. */ +bool GameLoadingScreen(void); +bool StartPreloadGraphics(uint64_t ticks); +bool StepPreloadGraphics(uint64_t ticks); +void ResetPreloadGraphics(void); +void PreloadUpdate(unsigned current,unsigned total); +bool VictoryTile(void); +void VictorySpin(void); +void ResetVictory(void); +bool DeathCameraActive(void); +bool StepDeathCamera(void); +void DrawPlayBorder(void); +bool DrawDeathCameraMessage(void); +bool DrawVictory(void); +bool StartEndText(void); +bool StepEndText(bool *done); +void ResetEndText(void); +bool GameVictoryPresentation(void); +/* Read-only death presentation: 0 pending/inactive, 1 turn, 2 fizzle, 3 hold. */ +unsigned GameDeathPresentation(uint32_t *seed); +unsigned NextMap(unsigned episode,unsigned map,exit_t exit); +typedef struct { unsigned kill,secret,treasure,seconds,par; int bonus; } levelratio_t; +extern levelratio_t LevelRatios[8]; +levelratio_t LevelStats(void); +bool DrawLevelCompleted(const levelratio_t *stats); +bool StartLevelIntermission(const levelratio_t *stats,uint64_t ticks); +bool StepLevelIntermission(uint64_t ticks,bool acknowledge,bool *leave); +bool LevelIntermissionCounting(void); +bool GameStep(uint64_t ticks); +void GameStop(void); +bool GameProbe(void); +/* Public trace result supports deterministic tests without an SDL renderer. */ +typedef struct { int32_t x,y; unsigned page,column,height; int side,grid,tile; } rayhit; +bool AsmRefresh(int fineangle,rayhit *hit); +bool ThreeDRefresh(void); +bool ThreeDRefreshPaused(void); +void ScalePost(unsigned x,unsigned width,unsigned height,const w3r_byte *column); +#include "WL_ACTOR.h" +#endif diff --git a/src/engine/WL_DEMO.c b/src/engine/WL_DEMO.c new file mode 100644 index 00000000..874bb3c6 --- /dev/null +++ b/src/engine/WL_DEMO.c @@ -0,0 +1,58 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_GAME.C PlayDemo / WL_PLAY.C PollControls. Original embedded WL6 chunks, + four 70-Hz tics per signed x/y/button command; no host input or fake RNG. */ +#include "WL_DEMO.h" +#include "WL_DEF.h" +#include "WL_SAVE.h" +#include "ID_CA.h" +#include "ID_FILE.h" +static const w3r_byte *stream; +static size_t end,cursor; +static unsigned buttons,held_buttons,source_map; +bool Demo_Progress(demo_progress *progress) +{ + if(!progress || !stream || end<4 || cursor<4 || cursor>end) return false; + progress->map=source_map; + progress->commands_total=(end-4)/3; + progress->commands_consumed=(cursor-4)/3; + progress->buttons=buttons; + return true; +} +int SimulationTics(void) { return Demo_Active()?4:1; } +static int Signed(unsigned value) { return value<128?(int)value:(int)value-256; } +bool Demo_Validate(const w3r_byte *data,size_t size,unsigned *map,size_t *length) +{ + if(!data || size<7 || !map || !length) return CA_Fail("Truncated demo header/commands"); + size_t n=CA_LE16(data+1); + if(data[0]>=60 || n<7 || n>size || (n-4)%3) return CA_Fail("Invalid demo map/length"); + for(size_t i=4;i100 || y< -100 || y>100) return CA_Fail("Demo control outside original limits"); + } + *map=data[0];*length=n;return true; +} +void Demo_Stop(void) { stream=NULL;end=cursor=0;buttons=held_buttons=source_map=0; } +bool Demo_Active(void) { return stream!=NULL; } +unsigned Demo_Buttons(void) { return buttons; } +void Demo_SuppressButtons(unsigned mask) { held_buttons&=~mask; } +bool Demo_Finished(void) { return !stream || cursor>=end || gamestate.died || playstate!=ex_playing; } +bool Demo_ReadTic(demo_command *command) +{ + if(Demo_Finished() || !command) return false; + unsigned previous=held_buttons;buttons=held_buttons=stream[cursor]; + command->buttons=buttons;command->x=Signed(stream[cursor+1]);command->y=Signed(stream[cursor+2]); + command->use=(buttons&8U)!=0 && !(previous&8U); + cursor+=3; + return true; +} +bool Demo_Start(unsigned number,uint64_t ticks) +{ + GameStop();if(number>=4) return CA_Fail("Invalid demo number"); + int chunk=T_DEMO0+(int)number; + if(!CA_CacheGrChunk(chunk)) return false; + unsigned map;size_t length; + if(!Demo_Validate(grsegs[chunk],grsizes[chunk],&map,&length) || !GameStartMap(ticks,map,3,0)) return false; + stream=grsegs[chunk];end=length;cursor=4;buttons=held_buttons=0;source_map=map; + if(GameDrawPaused()) return true; + GameStop();return false; +} diff --git a/src/engine/WL_DEMO.h b/src/engine/WL_DEMO.h new file mode 100644 index 00000000..a8ca86e9 --- /dev/null +++ b/src/engine/WL_DEMO.h @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_DEMO_H +#define WL_DEMO_H +#include "w3r_types.h" +#include +#include +#include +typedef struct { unsigned buttons;int x,y;bool use; } demo_command; +bool Demo_Validate(const w3r_byte *data,size_t size,unsigned *map,size_t *length); +bool Demo_Start(unsigned number,uint64_t ticks); +void Demo_Stop(void); +bool Demo_Active(void); +bool Demo_Finished(void); +/* Read one original four-tic command frame. */ +bool Demo_ReadTic(demo_command *command); +unsigned Demo_Buttons(void); +/* Preserve DOS buttonstate -> buttonheld latching after T_Attack suppression. */ +void Demo_SuppressButtons(unsigned mask); +/* Read-only playback diagnostics; command counts never advance simulation. */ +typedef struct { + unsigned map; + size_t commands_total,commands_consumed; + unsigned buttons; +} demo_progress; +bool Demo_Progress(demo_progress *progress); +#endif diff --git a/src/engine/WL_DISPLAY.c b/src/engine/WL_DISPLAY.c new file mode 100644 index 00000000..849ee18a --- /dev/null +++ b/src/engine/WL_DISPLAY.c @@ -0,0 +1,94 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "WL_DISPLAY.h" +#include "WL_MENU.h" +#include "ID_IN.h" +#include "ID_CA.h" +#include "ID_VH.h" +#include "ID_US_1.h" +#include +#include +static bool (*Get)(display_settings *),(*Set)(const display_settings *); +static unsigned selected; +static display_settings previous; +/* Window sizing is independent of the 4:3 DOS menu canvas and 3D render size. */ +typedef struct { int width,height; } window_preset; +static const window_preset window_presets[]={ + {640,480},{960,720},{1280,960}, + {960,600},{1280,800},{1600,1000},{1920,1200}, + {960,540},{1280,720},{1600,900},{1920,1080}, + {1680,720},{2560,1080}, + {1920,540},{2560,720} +}; +#define WINDOW_PRESET_COUNT (sizeof(window_presets)/sizeof(window_presets[0])) +static void CycleWindowSize(display_settings *s,bool backwards) +{ + size_t current=WINDOW_PRESET_COUNT; + for(size_t i=0;iwidth==window_presets[i].width && s->height==window_presets[i].height) { current=i;break; } + size_t next=current==WINDOW_PRESET_COUNT?(backwards?WINDOW_PRESET_COUNT-1:0): + (current+(backwards?WINDOW_PRESET_COUNT-1:1))%WINDOW_PRESET_COUNT; + s->scale=0;s->width=window_presets[next].width;s->height=window_presets[next].height; +} +void Display_Connect(bool (*get)(display_settings *),bool (*set)(const display_settings *)) { Get=get;Set=set; } +bool Display_Available(void) { return Get && Set; } +static bool Text(int x,int y,const char *s) { PrintX=x;PrintY=y;return US_Print(s); } +static bool Draw(const display_settings *s) +{ + ClearMScreen();DrawStripes(10);DrawWindow(20,34,280,144,BKGDCOLOR); + fontnumber=1;fontcolor=TEXTCOLOR;int w,h; + if(!VW_MeasurePropString("Display",&w,&h) || !Text((320-w)/2,14,"Display")) return false; + fontnumber=0; + static const char *const labels[]={"Fullscreen","Menu scaling","Window size","3D renderer","Internal 3D size","Gameplay aspect","VSync","Texture filter","Smooth rendering","Reset defaults"}; + for(unsigned i=0;i<10;++i) { + char value[40];fontcolor=i==selected?HIGHLIGHT:TEXTCOLOR; + if(i==0) (void)snprintf(value,sizeof(value),"%s",s->pending?"Switching...":s->fullscreen?"On":"Off"); + else if(i==1) (void)snprintf(value,sizeof(value),"%s",s->integer?"Integer":"Fit"); + else if(i==2) (void)snprintf(value,sizeof(value),"%d x %d",s->width,s->height); + else if(i==3) (void)snprintf(value,sizeof(value),"%s",s->high_resolution?"Enhanced":"Original"); + else if(i==4) { if(s->render_auto) (void)snprintf(value,sizeof(value),"Auto (desktop)"); + else (void)snprintf(value,sizeof(value),"%u x %u",s->render_width,s->render_height); } + else if(i==5) { static const char *const names[]={"Auto","4:3","16:9","16:10","21:9","32:9"};(void)snprintf(value,sizeof(value),"%s",names[s->aspect<6?s->aspect:0]); } + else if(i==6) (void)snprintf(value,sizeof(value),"%s",s->vsync?"On":"Off"); + else if(i==7) (void)snprintf(value,sizeof(value),"%s",s->linear?"Linear":"Nearest"); + else if(i==8) (void)snprintf(value,sizeof(value),"%s",s->smooth?"On":"Off"); + else (void)snprintf(value,sizeof(value),"Enter"); + if(!Text(56,39+(int)i*11,labels[i]) || !Text(176,39+(int)i*11,value)) return false; + } + fontcolor=TEXTCOLOR; + if(!Text(26,166,*s->error?"Display change failed; try again.":(s->integer && (s->pixel_width<320 || s->pixel_height<240)?"Small window uses fit scaling.":(s->smooth && !s->high_resolution?"Smooth needs Enhanced 3D.":"F12 saves a screenshot.")))) return false; + return VWB_DrawPic(24,37+(int)selected*11,C_CURSOR1PIC) && VWB_DrawPic(112,184,C_MOUSELBACKPIC); +} +bool BeginDisplayMenu(void) +{ + if(!Display_Available() || !Get(&previous)) return false; + selected=0;IN_ClearKeysDown();return Draw(&previous); +} +int HandleDisplayMenu(void) +{ + if(IN_ConsumePress(sc_Escape)) return -1; + display_settings s;if(!Display_Available() || !Get(&s)) return -1; + bool up=IN_ConsumePress(sc_UpArrow),down=IN_ConsumePress(sc_DownArrow); + bool left=IN_ConsumePress(sc_LeftArrow),right=IN_ConsumePress(sc_RightArrow),enter=IN_ConsumePress(sc_Enter); + if(up || down) selected=(selected+(up?9U:1U))%10U; + if((left || right || enter) && !s.pending) { + if(selected==0) s.fullscreen=!s.fullscreen; + else if(selected==1) s.integer=!s.integer; + else if(selected==2) CycleWindowSize(&s,left); + else if(selected==3) s.high_resolution=!s.high_resolution; + else if(selected==4) { + unsigned n=s.render_auto?3U:s.render_width==1920?2U:s.render_width==1280?1U:0U; + n=left?(n+3)%4:(n+1)%4; + static const unsigned widths[]={640,1280,1920},heights[]={480,720,1080}; + s.render_auto=n==3;if(n<3) { s.render_width=widths[n];s.render_height=heights[n]; } + } else if(selected==5) s.aspect=(s.aspect+(left?5U:1U))%6U; + else if(selected==6) s.vsync=!s.vsync; + else if(selected==7) s.linear=!s.linear; + else if(selected==8) s.smooth=!s.smooth; + else if(enter) { s.smooth=false;s.fullscreen=s.integer=s.high_resolution=s.render_auto=s.vsync=s.linear=false;s.aspect=0;s.scale=3;s.render_width=640;s.render_height=480; } + (void)Set(&s);if(!Get(&s)) return -1; + } + if(up || down || left || right || enter || memcmp(&previous,&s,sizeof(s))) { + previous=s;return Draw(&s)?0:-3; + } + return 0; +} diff --git a/src/engine/WL_DISPLAY.h b/src/engine/WL_DISPLAY.h new file mode 100644 index 00000000..9edbabff --- /dev/null +++ b/src/engine/WL_DISPLAY.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_DISPLAY_H +#define WL_DISPLAY_H +#include "platform/display_settings.h" +/* The native application connects its two settings operations. Headless + engine tests retain no dependency on SDL or a video device. */ +void Display_Connect(bool (*get)(display_settings *),bool (*set)(const display_settings *)); +bool Display_Available(void); +bool BeginDisplayMenu(void); +int HandleDisplayMenu(void); +#endif diff --git a/src/engine/WL_DRAW.c b/src/engine/WL_DRAW.c new file mode 100644 index 00000000..dd99030f --- /dev/null +++ b/src/engine/WL_DRAW.c @@ -0,0 +1,249 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_DR_A.ASM quadrant initialization and vertcheck/horizcheck translated + directly to bounded C; WL_DRAW.C wall/door hits, texture flips and height. */ +#include "WL_DEF.h" +#include "WL_RENDER.h" +#include "WL_DEMO.h" +#include "ID_CA.h" +#include "ID_PM.h" +#include "ID_VL.h" +#include +unsigned wallheight[MAXVIEWWIDTH]; +static bool drawing_paused; +static uint64_t render_serial; +uint64_t WL_RenderSerial(void) { return render_serial; } +static int32_t viewx,viewy; +static uint32_t viewsin,viewcos; +static int32_t PartialStep(int32_t step,uint16_t partial) +{ + int64_t magnitude=step<0 ? -(int64_t)step : step; + int32_t result=(int32_t)(magnitude*partial/65536); + return step<0 ? -result : result; +} +static void SetView(void) +{ + viewsin=sintable[player.angle]; viewcos=sintable[player.angle+90]; + viewx=player.x-FixedByFrac(FOCALLENGTH,viewcos); + viewy=player.y+FixedByFrac(FOCALLENGTH,viewsin); +} +static unsigned CalcHeight(int32_t x,int32_t y) +{ + int32_t nx=FixedByFrac(x-viewx,viewcos)-FixedByFrac(y-viewy,viewsin); + if (nx=360))) return CA_Fail("Invalid ray request"); + if(!world) SetView(); + int32_t rayx=world?world->x:viewx,rayy=world?world->y:viewy; + const w3r_byte (*tiles)[64]=world?world->scene->tiles:(const w3r_byte (*)[64])tilemap; + const doorobj_t *doors=world?world->scene->doors:doorobjlist; + unsigned door_count=world?world->scene->door_count:doornum; + int32_t push_offset=world?world->scene->push_offset:(int32_t)(pwallpos*1024); + angle%=3600; if (angle<0) angle+=3600; + int dx,dy; int32_t xs,ys; uint16_t xp,yp; + uint16_t xdown=(uint16_t)((uint32_t)rayx&65535),ydown=(uint16_t)((uint32_t)rayy&65535); + uint16_t xup=(uint16_t)(65536U-xdown),yup=(uint16_t)(65536U-ydown); + if (angle<900) { dx=1;dy=-1;xs=finetangent[899-angle];ys=-finetangent[angle];xp=xup;yp=ydown; } + else if (angle<1800) { dx=-1;dy=-1;xs=-finetangent[angle-900];ys=-finetangent[1799-angle];xp=xdown;yp=ydown; } + else if (angle<2700) { dx=-1;dy=1;xs=-finetangent[2699-angle];ys=finetangent[angle-1800];xp=xdown;yp=yup; } + else { dx=1;dy=1;xs=finetangent[angle-2700];ys=finetangent[3599-angle];xp=xup;yp=yup; } + int xtile=WL_FloorShift(rayx,16)+dx,ytile=WL_FloorShift(rayy,16)+dy; + int64_t yi=(int64_t)rayy+PartialStep(ys,xp),xi=(int64_t)rayx+PartialStep(xs,yp); + bool vertical=!(dy<0 ? WL_FloorShift(yi,16)<=ytile : WL_FloorShift(yi,16)>=ytile); + for (unsigned crossings=0;crossings<256;++crossings) { + int tx=vertical ? xtile : WL_FloorShift(xi,16); + int ty=vertical ? WL_FloorShift(yi,16) : ytile; + if (tx<0 || ty<0 || tx>=64 || ty>=64) return CA_Fail("Ray escaped map perimeter"); + unsigned tile=tiles[tx][ty]; bool pass=tile==0; + int32_t hx=0,hy=0; unsigned page=0,column=0; int side=vertical ? 1 : 0; + if ((tile&0xc0)==0xc0) { + /* WL_DR_A.ASM vertpushwall/horizpushwall: project the original + 0..63 partial step and pass rays that leave this tile. */ + int64_t mid=vertical ? yi+WL_FloorShift((int64_t)ys*push_offset,16) : + xi+WL_FloorShift((int64_t)xs*push_offset,16); + if (WL_FloorShift(mid,16)!=(vertical ? ty : tx)) pass=true; + else { + int32_t offset=push_offset; + hx=vertical ? xtile*65536+(dx<0 ? 65536-offset : offset) : (int32_t)mid; + hy=vertical ? (int32_t)mid : ytile*65536+(dy<0 ? 65536-offset : offset); + column=((uint32_t)mid>>10)&63; + if (vertical ? dx<0 : dy>0) column=63-column; + page=((tile&63)-1)*2+(vertical ? 1U : 0U); + side=vertical ? 4 : 3; + } + } else if (tile&128) { + unsigned door=tile&127; + if (door>=door_count) return CA_Fail("Invalid door index in ray"); + int64_t mid=vertical ? yi+WL_FloorShift(ys,1) : xi+WL_FloorShift(xs,1); + int before=vertical ? ty : tx; + if (WL_FloorShift(mid,16)!=before || (uint16_t)mid>10)&63; + unsigned lock=doors[door].lock; + page=PMSpriteStart-8+(lock==0 ? 0 : lock==5 ? 4 : 6)+(vertical ? 1U : 0U); + side=2; + } + } else if (tile) { + unsigned wall=tile&63; + /* Original wall tables leave index zero at page zero. A door + beside floor marks that floor 0x40 (e.g. owned E2M3). */ + if (vertical) { + hx=xtile*65536+(dx<0 ? 65536 : 0); hy=(int32_t)yi; + column=((uint32_t)yi>>10)&63; if (dx<0) column=63-column; + page=wall ? (wall-1)*2+1 : 0; + if ((tile&64) && tx-dx>=0 && tx-dx<64 && (tiles[tx-dx][ty]&128)) page=PMSpriteStart-8+3; + } else { + hx=(int32_t)xi; hy=ytile*65536+(dy<0 ? 65536 : 0); + column=((uint32_t)xi>>10)&63; if (dy>0) column=63-column; + page=wall ? (wall-1)*2 : 0; + if ((tile&64) && ty-dy>=0 && ty-dy<64 && (tiles[tx][ty-dy]&128)) page=PMSpriteStart-8+2; + } + } + if (!pass) { + if (page>=PMSpriteStart) return CA_Fail("Ray selected a non-wall texture"); + hit->x=hx;hit->y=hy;hit->page=page;hit->column=column;hit->height=world?0:CalcHeight(hx,hy); + hit->side=side;hit->grid=side==2 ? (int)tile : vertical ? xtile : ytile;hit->tile=(int)tile; + return true; + } + if(mark) spotvis[tx][ty]=true; + if (vertical) { + xtile+=dx; yi+=ys; + vertical=!(dy<0 ? WL_FloorShift(yi,16)<=ytile : WL_FloorShift(yi,16)>=ytile); + } else { + ytile+=dy; xi+=xs; + vertical=dx<0 ? WL_FloorShift(xi,16)<=xtile : WL_FloorShift(xi,16)>=xtile; + } + } + return CA_Fail("Ray traversal exceeded map bounds"); +} +bool AsmRefresh(int angle,rayhit *hit) { return CastRay(angle,hit,true,NULL); } +bool WL_RenderRay(int angle,rayhit *hit) { return CastRay(angle,hit,false,NULL); } +bool WL_RenderRayWorld(int angle,rayhit *hit,const wl_ray_world *world) +{ return world && world->scene && CastRay(angle,hit,false,world); } +/* WL_DRAW.C vgaCeiling: episode/map-specific original ceiling palette. */ +static const w3r_byte vgaCeiling[60]={ + 0x1d,0x1d,0x1d,0x1d,0x1d,0x1d,0x1d,0x1d,0x1d,0xbf, + 0x4e,0x4e,0x4e,0x1d,0x8d,0x4e,0x1d,0x2d,0x1d,0x8d, + 0x1d,0x1d,0x1d,0x1d,0x1d,0x2d,0xdd,0x1d,0x1d,0x98, + 0x1d,0x9d,0x2d,0xdd,0xdd,0x9d,0x2d,0x4d,0x1d,0xdd, + 0x7d,0x1d,0x2d,0x2d,0xdd,0xd7,0x1d,0x1d,0x1d,0x2d, + 0x1d,0x1d,0x1d,0x1d,0xdd,0xdd,0x7d,0xdd,0xdd,0xdd, +}; +unsigned WL_CeilingColor(void) { return vgaCeiling[gamestate.episode*10+gamestate.mapon]; } +bool ThreeDRefresh(void) +{ + ++render_serial; /* Presentation invalidation; never saved or simulated. */ + memset(spotvis,0,sizeof(spotvis)); + /* DOS marks only cells crossed by rays, not the starting player cell. */ + for (unsigned y=0;yx,ob->y,ACTORSIZE,&ob->viewx,&ob->viewheight,&ob->transx,&ob->transy); +} +bool TransformTile(int tx,int ty,int *x,int *height) +{ + int32_t nx,ny; + Transform(tx*TILEGLOBAL+32768,ty*TILEGLOBAL+32768,0x2000,x,height,&nx,&ny); + return *height && nx-TILEGLOBAL/2 && nyviewx)/8; + int angle=(viewangle-180)-(ob->obclass==rocketobj ? ob->angle : dirangle[ob->dir])+ANGLES/16; + angle%=ANGLES;if (angle<0) angle+=ANGLES; + return ob->state->rotate==2 ? 4*(angle/(ANGLES/2)) : angle/(ANGLES/8); +} +bool DrawScaleds(void) +{ + /* Original MAXVISABLE limit and stable least-height selection. */ + struct { int x,height,shape; } vis[50];unsigned count=0; + for (unsigned i=0;ishapenum<0 || !spotvis[ob->tilex][ob->tiley]) continue; + int x=0,height=0; + if (TransformTile(ob->tilex,ob->tiley,&x,&height) && ob->bonus && !gamestate.died && !drawing_paused) { GetBonus(ob);continue; } + if (height && count<49) { vis[count].x=x;vis[count].height=height;vis[count++].shape=ob->shapenum; } + } + for (objtype *current=player.next;current;current=current->next) { + objtype copy=*current,*ob=drawing_paused?©:current; + if (!ob->state || !ob->state->shapenum) continue; + bool visible=spotvis[ob->tilex][ob->tiley]; + for (int dx=-1;dx<=1;++dx) for (int dy=-1;dy<=1;++dy) { + int x=ob->tilex+dx,y=ob->tiley+dy; + if (x>=0 && y>=0 && x<64 && y<64 && !tilemap[x][y] && spotvis[x][y]) visible=true; + } + if (!visible) { ob->flags&=~FL_VISABLE;continue; } + ob->active=true;TransformActor(ob); + /* DOS retains the prior visible flag on the too-close branch. */ + if (!ob->viewheight) continue; + ob->flags|=FL_VISABLE; + if (count<49) { + vis[count].x=ob->viewx;vis[count].height=ob->viewheight; + vis[count++].shape=ob->state->shapenum+(ob->state->rotate ? CalcRotate(ob) : 0); + } + } + for (unsigned i=0;iprevious_ns=0;clock->current_ns=0;clock->ready=false; } +} +void WL_FrameClockObserve(wl_frame_clock *clock,uint64_t tick_ns) +{ + if(!clock) return; + if(!clock->ready || tick_nscurrent_ns) { + clock->previous_ns=tick_ns;clock->current_ns=tick_ns;clock->ready=true; + return; + } + if(tick_ns==clock->current_ns) return; + clock->previous_ns=clock->current_ns;clock->current_ns=tick_ns; +} +double WL_FrameClockAlpha(const wl_frame_clock *clock,uint64_t now_ns) +{ + if(!clock || !clock->ready || clock->current_ns<=clock->previous_ns) return 0.0; + /* Interpolate from previous authoritative state to current state with + one tick of presentation latency, avoiding future-state prediction. */ + if(now_ns<=clock->current_ns) return 0.0; + uint64_t span=clock->current_ns-clock->previous_ns; + uint64_t elapsed=now_ns-clock->current_ns; + if(elapsed>=span) return 1.0; + return (double)elapsed/(double)span; +} + +uint64_t WL_TicksFromNS(uint64_t ns) +{ return TimeCount_FromNS(ns); } +uint64_t WL_TickNS(uint64_t tick) +{ + if(tick/70>UINT64_MAX/1000000000U) return UINT64_MAX; + uint64_t whole=tick/70*1000000000U,part=(tick%70*1000000000U+69)/70; + return whole>UINT64_MAX-part?UINT64_MAX:whole+part; +} +bool WL_TickNext(uint64_t *completed,uint64_t now_ns) +{ + if(!completed || *completed>=WL_TicksFromNS(now_ns)) return false; + ++*completed;return true; +} +uint64_t WL_FrameDeadline(uint64_t now_ns,unsigned fps) +{ + if(fps<1 || fps>1000) return now_ns; + uint64_t frame=now_ns/1000000000U*fps+(now_ns%1000000000U)*fps/1000000000U+1; + if(frame/fps>UINT64_MAX/1000000000U) return UINT64_MAX; + uint64_t whole=frame/fps*1000000000U,part=(frame%fps*1000000000U+fps-1)/fps; + return whole>UINT64_MAX-part?UINT64_MAX:whole+part; +} + +uint64_t WL_PresentationDeadline(uint64_t start_ns,uint64_t finish_ns,double refresh,bool sync_paced) +{ + if(!(refresh>=1.0 && refresh<=10000.0)) refresh=60.0; + if(refresh>240.0 || sync_paced) refresh=240.0; + double period=1000000000.0/refresh; + uint64_t span=(uint64_t)period; + if((double)spanUINT64_MAX-span?UINT64_MAX:start_ns+span; + return finish_ns>deadline?finish_ns:deadline; +} diff --git a/src/engine/WL_FRAME_CLOCK.h b/src/engine/WL_FRAME_CLOCK.h new file mode 100644 index 00000000..0e3f0dc3 --- /dev/null +++ b/src/engine/WL_FRAME_CLOCK.h @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_FRAME_CLOCK_H +#define WL_FRAME_CLOCK_H +#include +#include +/* Presentation-only timing utility. No gameplay clock or RNG is modified. + Call after authoritative simulation stepping, never instead of it. */ +typedef struct { uint64_t previous_ns,current_ns; bool ready; } wl_frame_clock; +void WL_FrameClockReset(wl_frame_clock *clock); +void WL_FrameClockObserve(wl_frame_clock *clock,uint64_t tick_ns); +/* 0..1 interpolation fraction, clamped against zero/invalid intervals. */ +double WL_FrameClockAlpha(const wl_frame_clock *clock,uint64_t now_ns); +/* Rational deadlines; fixed simulation debt is consumed one tick at a time. + Callers bound catch-up work without dropping debt. */ +uint64_t WL_TicksFromNS(uint64_t ns); +uint64_t WL_TickNS(uint64_t tick); +bool WL_TickNext(uint64_t *completed,uint64_t now_ns); +uint64_t WL_FrameDeadline(uint64_t now_ns,unsigned fps); +/* Start-anchored pacing subtracts time already spent rendering/presenting. + A blocking VSync present owns monitor pacing; retain only the 240 Hz ceiling. */ +uint64_t WL_PresentationDeadline(uint64_t start_ns,uint64_t finish_ns,double refresh,bool sync_paced); +#endif diff --git a/src/engine/WL_GAME.c b/src/engine/WL_GAME.c new file mode 100644 index 00000000..22a27489 --- /dev/null +++ b/src/engine/WL_GAME.c @@ -0,0 +1,119 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_GAME.C SetupGameLevel/ScanInfoPlane, and WL_ACT1.C SpawnDoor marking. + Original objects and enemies are spawned by ScanInfoPlane. */ +#include "WL_DEF.h" +#include "ID_CA.h" +#include "ID_PM.h" +#include +objtype player; +w3r_byte tilemap[64][64]; +doorobj_t doorobjlist[64]; +unsigned doornum; +exit_t playstate; +bool NewGame(unsigned difficulty,unsigned episode) +{ + if (difficulty>3 || episode>5) return CA_Fail("Invalid episode/difficulty"); + memset(&gamestate,0,sizeof(gamestate)); + memset(LevelRatios,0,sizeof(LevelRatios)); + gamestate.episode=(int)episode;gamestate.difficulty=(int)difficulty; + gamestate.health=100;gamestate.ammo=8;gamestate.lives=3; + gamestate.nextextra=40000; + gamestate.weapon=gamestate.bestweapon=gamestate.chosenweapon=wp_pistol; + return true; +} +unsigned NextMap(unsigned episode,unsigned map,exit_t exit) +{ + static const unsigned back[]={1,1,7,3,5,3}; /* WL_GAME.C ElevatorBackTo */ + /* Floor nine ends an episode; it must never advance to the secret floor. + Victory is handled separately by GameStep; return the invalid-map sentinel. */ + if (episode>5 || map>9 || map==8 || + (exit!=ex_completed && exit!=ex_secretlevel)) return 60; + return episode*10+(map==9 ? back[episode] : exit==ex_secretlevel ? 9 : map+1); +} +void ShutdownGameLevel(void) { ResetVictory(); CA_UncacheMap(); PM_Shutdown(); doornum=0; InitObjects();ResetPushwalls(); } +/* Original maps can contain unused floor cells on the outer edge (E1M3). + Only initially reachable space (including closed doors) must be enclosed. This + keeps malformed maps from letting rays or movement leave the 64x64 grid. */ +static bool ValidateEnclosure(void) +{ + bool seen[64][64]={{false}}; + unsigned queue[4096],head=0,tail=0; + queue[tail++]=(unsigned)(player.tiley*64+player.tilex);seen[player.tilex][player.tiley]=true; + static const int dx[]={1,0,-1,0},dy[]={0,1,0,-1}; + while (head5 || gamestate.mapon<0 || gamestate.mapon>9 || + gamestate.difficulty<0 || gamestate.difficulty>3) return CA_Fail("Invalid game selection"); + if (!CA_CacheMap((unsigned)(gamestate.episode*10+gamestate.mapon)) || !PM_Startup()) { ShutdownGameLevel(); return false; } + InitObjects();ResetPushwalls(); + gamestate.killcount=gamestate.killtotal=gamestate.treasurecount=gamestate.treasuretotal=0; + gamestate.secretcount=gamestate.secrettotal=0;gamestate.TimeCount=0; + gamestate.attackframe=gamestate.weaponframe=gamestate.attackcount=gamestate.faceframe=0; + gamestate.died=gamestate.victoryflag=false;playstate=ex_playing; + ResetStatus(); + const maptype *map=CA_Map(); unsigned starts=0; + memset(tilemap,0,sizeof(tilemap)); doornum=0; + for (unsigned y=0;y<64;++y) for (unsigned x=0;x<64;++x) { + unsigned tile=map->planes[0][y*64+x]; + if (tile>143) { (void)CA_Fail("Invalid map area number"); goto bad; } + if (tile==106 || tile>=107) tile=0; /* AMBUSHTILE becomes area floor. */ + if (tile>63 && (tile<90 || tile>101)) { (void)CA_Fail("Unsupported/invalid wall tile %u",tile); goto bad; } + tilemap[x][y]=(w3r_byte)tile; + unsigned spawn=map->planes[1][y*64+x]; + if (spawn>=19 && spawn<=22) { + ++starts; player.x=(int32_t)(x*65536+32768); player.y=(int32_t)(y*65536+32768); + player.tilex=(int)x; player.tiley=(int)y; + player.angle=(1-(int)(spawn-19))*90; + if (player.angle<0) player.angle+=360; + } + } + for (unsigned y=1;y<63;++y) for (unsigned x=1;x<63;++x) { + unsigned tile=map->planes[0][y*64+x]; + if (tile>=90 && tile<=101) { + if (doornum>=64) { (void)CA_Fail("Too many doors"); goto bad; } + doorobj_t *door=&doorobjlist[doornum]; + door->action=dr_closed;door->position=0;door->ticcount=0; + door->x=x; door->y=y; door->vertical=(tile%2)==0; door->lock=(tile-90)/2; + tilemap[x][y]=(w3r_byte)(128+doornum++); + if (door->vertical) { tilemap[x][y-1]|=64; tilemap[x][y+1]|=64; } + else { tilemap[x-1][y]|=64; tilemap[x+1][y]|=64; } + } + } + if (!ScanInfoPlane()) goto bad; + if (starts!=1 || !TryMove(&player)) { (void)CA_Fail("Invalid/obstructed player spawn"); goto bad; } + if (!ValidateEnclosure()) goto bad; + /* Validate and cache every wall page referenced by this level before play. */ + for (unsigned y=0;y<64;++y) for (unsigned x=0;x<64;++x) { + unsigned tile=tilemap[x][y]; + if (!tile || (tile&128)) continue; + tile&=63; + if (tile && (tile*2-1>=PMSpriteStart)) { (void)CA_Fail("Wall texture outside VSWAP wall pages"); goto bad; } + if (tile && (!PM_GetPage((tile-1)*2,NULL) || !PM_GetPage((tile-1)*2+1,NULL))) goto bad; + } + for (unsigned i=0;i<8;++i) if (!PM_GetPage(PMSpriteStart-8+i,NULL)) goto bad; + w3r_byte pixels[4096],mask[4096]; + for (unsigned sprite=0;sprite +#include +static high_score table[HIGH_SCORE_COUNT]; +static bool initialized,writable; +static char path[4096],edit[HIGH_NAME_MAX+1]; +static int entry=-1; +static size_t cursor; +static uint64_t blink_at; +static bool visible; +void HighScores_Reset(void) +{ + static const char *const names[]={"id software-'92","Adrian Carmack","John Carmack","Kevin Cloud","Tom Hall","John Romero","Jay Wilbur"}; + memset(table,0,sizeof(table)); + for(unsigned i=0;i>(i*8)); } +static uint32_t Hash(const unsigned char *p,size_t n) +{ uint32_t h=2166136261U;while(n--) h=(h^*p++)*16777619U;return h; } +bool HighScores_Load(const char *directory) +{ + HighScores_Reset();writable=false;path[0]=0; + if(!directory || !*directory) return CA_Fail("High-score storage unavailable"); + int n=snprintf(path,sizeof(path),"%s/highscores.w3h",directory); + if(n<0 || (size_t)n>=sizeof(path)) { path[0]=0;return CA_Fail("High-score path too long"); } + FILE *f=SaveFile_Open(path); + if(!f) { writable=SaveFile_Missing(path);return writable?true:CA_Fail("Cannot read high scores"); } + unsigned char bytes[460];size_t count=fread(bytes,1,sizeof(bytes),f);int extra=fgetc(f),error=ferror(f); + if(fclose(f)!=0) error=1; + if(error || count!=sizeof(bytes) || extra!=EOF || memcmp(bytes,"W3HS\1\7\0\0",8) || Get32(bytes+456)!=Hash(bytes,456)) + return CA_Fail("Invalid or unsupported high-score file; preserved"); + high_score loaded[HIGH_SCORE_COUNT]={0}; + for(unsigned i=0;i10 || p[59]>5) + return CA_Fail("Invalid high-score entry; file preserved"); + size_t len=strlen((const char *)p); + for(size_t j=0;j126) return CA_Fail("Invalid high-score name; file preserved"); + memcpy(loaded[i].name,p,len+1);loaded[i].completed=p[58];loaded[i].episode=p[59];loaded[i].score=Get32(p+60); + if(i && (loaded[i].score>loaded[i-1].score || (loaded[i].score==loaded[i-1].score && loaded[i].completed>loaded[i-1].completed))) + return CA_Fail("Unsorted high-score file; preserved"); + } + memcpy(table,loaded,sizeof(table));writable=true;return true; +} +bool HighScores_Save(void) +{ + if(!writable || !*path) return CA_Fail("High-score storage unavailable or protected"); + unsigned char bytes[460]={0};memcpy(bytes,"W3HS\1\7\0\0",8); + const high_score *scores=HighScores_Table(); + for(unsigned i=0;i10 || episode>5) return -1; + for(unsigned i=0;itable[i].score || (score==table[i].score && completed>table[i].completed)) { + for(unsigned j=HIGH_SCORE_COUNT-1;j>i;--j) table[j]=table[j-1]; + memset(&table[i],0,sizeof(table[i]));table[i].score=score;table[i].completed=completed;table[i].episode=episode;return (int)i; + } + return -1; +} +static bool DrawEntry(void) +{ + if(!DrawHighScores()) return false; + fontnumber=0;fontcolor=15;PrintX=32;PrintY=76+16*entry; + if(!US_Print(edit)) return false; + if(visible) { + char prefix[HIGH_NAME_MAX+1];memcpy(prefix,edit,cursor);prefix[cursor]=0; + int w,h;if(!VW_MeasurePropString(prefix,&w,&h)) return false; + /* ID_US_1.C USL_XORICursor uses the original I-bar glyph 0x80. */ + px=32+w-1;py=PrintY;return VW_DrawPropString("\x80"); + } + return true; +} +bool BeginHighScoreEntry(int rank,uint64_t ticks) +{ + if(rank<0 || rank>=HIGH_SCORE_COUNT) return false; + entry=rank;edit[0]=0;cursor=0;visible=true;blink_at=ticks+35;IN_ClearKeysDown();return DrawEntry(); +} +int HandleHighScoreEntry(uint64_t ticks) +{ + if(entry<0) return 1; + bool accept=IN_ConsumePress(sc_Enter),cancel=IN_ConsumePress(sc_Escape); + if(accept || cancel) { + /* DOS Escape cancels only the typed name; the qualifying score stays. */ + if(accept) (void)snprintf(table[entry].name,sizeof(table[entry].name),"%s",edit); + entry=-1;IN_ClearKeysDown();return 1; + } + size_t n=strlen(edit); + if(IN_ConsumePress(sc_LeftArrow) && cursor) --cursor; + if(IN_ConsumePress(sc_RightArrow) && cursor=HIGH_NAME_MAX || w>=100) continue; + memmove(edit+cursor+1,edit+cursor,n-cursor+1);edit[cursor++]=ch;++n; + } + if(ticks>=blink_at) { uint64_t count=(ticks-blink_at)/35+1;blink_at+=count*35;if(count%2) visible=!visible; } + return DrawEntry()?0:-1; +} diff --git a/src/engine/WL_HIGHSCORES.h b/src/engine/WL_HIGHSCORES.h new file mode 100644 index 00000000..7e07be14 --- /dev/null +++ b/src/engine/WL_HIGHSCORES.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_HIGHSCORES_H +#define WL_HIGHSCORES_H +#include +#include +#define HIGH_SCORE_COUNT 7 +#define HIGH_NAME_MAX 57 +typedef struct { char name[HIGH_NAME_MAX+1];uint32_t score;unsigned completed,episode; } high_score; +void HighScores_Reset(void); +const high_score *HighScores_Table(void); +/* Invalid/future files remain untouched; in-memory defaults still work. */ +bool HighScores_Load(const char *directory); +bool HighScores_Save(void); +int HighScores_Insert(uint32_t score,unsigned completed,unsigned episode); +bool BeginHighScoreEntry(int rank,uint64_t ticks); +/* 0 pending, 1 finished, -1 drawing failure. */ +int HandleHighScoreEntry(uint64_t ticks); +#endif diff --git a/src/engine/WL_INTER.c b/src/engine/WL_INTER.c new file mode 100644 index 00000000..92835fe0 --- /dev/null +++ b/src/engine/WL_INTER.c @@ -0,0 +1,288 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_INTER.C DrawHighScores: original default table from ID_US_1.C. + Native scores keep original qualification and fixed-width number glyphs. */ +#include "WL_MENU.h" +#include "ID_VH.h" +#include "ID_CA.h" +#include "ID_US_1.h" +#include "WL_HIGHSCORES.h" +#include +bool DrawHighScores(void) +{ + const high_score *scores=HighScores_Table(); + ClearMScreen(); DrawStripes(10); + if (!VWB_DrawPic(48,0,HIGHSCORESPIC) || !VWB_DrawPic(32,68,C_NAMEPIC) || + !VWB_DrawPic(160,68,C_LEVELPIC) || !VWB_DrawPic(224,68,C_SCOREPIC)) return false; + fontnumber = 0; fontcolor = 15; + for (int i = 0; i < 7; ++i) { + int width, height;char level[16],score[16],episode[16]; + (void)snprintf(level,sizeof(level),"%u",scores[i].completed); + (void)snprintf(score,sizeof(score),"%u",scores[i].score); + (void)snprintf(episode,sizeof(episode),"E%u/L",scores[i].episode+1); + for(char *p=level;*p;++p) *p=(char)((unsigned char)*p+129U-'0'); + for(char *p=score;*p;++p) *p=(char)((unsigned char)*p+129U-'0'); + PrintX = 32; PrintY = 76 + 16*i; + if (!US_Print(scores[i].name) || !VW_MeasurePropString(level,&width,&height)) return false; + PrintX = 22*8-width-6; + if (!US_Print(episode) || !US_Print(level) || !VW_MeasurePropString(score,&width,&height)) return false; + PrintX = 34*8-8-width; + if (!US_Print(score)) return false; + } + return true; +} + +/* WL_INTER.C LevelCompleted: original par times, integer ratios and bonuses. + The counting/sound/breathing state machine below shares this result drawing. */ +#include "WL_DEF.h" +#include +#include +#include +levelratio_t LevelRatios[8]; +levelratio_t LevelStats(void) +{ + static const unsigned par[6][8]={ + {90,120,120,210,180,180,150,150}, + {90,210,180,120,240,360,60,180}, + {90,90,150,150,210,150,120,360}, + {120,120,90,60,270,210,120,270}, + {150,90,150,150,240,180,270,210}, + {390,240,270,360,300,330,330,510} + }; + levelratio_t r={0}; + r.seconds=gamestate.TimeCount/70; + if (r.seconds>99*60) r.seconds=99*60; + if (gamestate.mapon>=8) { r.bonus=15000;return r; } + r.par=par[gamestate.episode][gamestate.mapon]; + if (gamestate.killtotal) r.kill=(unsigned)(gamestate.killcount*100/gamestate.killtotal); + if (gamestate.secrettotal) r.secret=(unsigned)(gamestate.secretcount*100/gamestate.secrettotal); + if (gamestate.treasuretotal) r.treasure=(unsigned)(gamestate.treasurecount*100/gamestate.treasuretotal); + r.bonus=(int)(r.seconds='0' && ch<='9') pic=L_NUM0PIC+ch-'0'; + else if (ch>='A' && ch<='Z') pic=L_APIC+ch-'A'; + else if (ch==':') { pic=L_COLONPIC;advance=8; } + else if (ch=='\'') { pic=L_APOSTROPHEPIC;advance=8; } + else if (ch=='!') { pic=L_EXPOINTPIC;advance=8; } + else if (ch=='%') pic=L_PERCENTPIC; + if (pic>=0 && !VWB_DrawPic(nx,ny,pic)) return false; + nx+=advance; + } + return true; +} +static bool WriteNumber(int right,int y,unsigned value) +{ + char text[16];(void)snprintf(text,sizeof(text),"%u",value); + return Write(right-(int)strlen(text)*2,y,text); +} +bool DrawLevelCompleted(const levelratio_t *r) +{ + VWB_Bar(0,0,320,160,127); + if (!VWB_DrawPic(0,16,L_GUYPIC)) return false; + if (gamestate.mapon>=8) return Write(14,4,"secret floor\n completed!") && Write(10,16,"15000 bonus!") && DrawStatus(); + char time[16],par[16]; + (void)snprintf(time,sizeof(time),"%02u:%02u",r->seconds/60,r->seconds%60); + (void)snprintf(par,sizeof(par),"%02u:%02u",r->par/60,r->par%60); + return Write(14,2,"floor\ncompleted") && WriteNumber(28,2,(unsigned)gamestate.mapon+1) && + Write(14,7,"bonus") && WriteNumber(36,7,(unsigned)r->bonus) && + Write(16,10,"time") && Write(26,10,time) && Write(16,12,"par") && Write(26,12,par) && + Write(9,14,"kill ratio") && Write(5,16,"secret ratio") && Write(1,18,"treasure ratio") && + WriteNumber(37,14,r->kill) && WriteNumber(37,16,r->secret) && WriteNumber(37,18,r->treasure) && + Write(37,14,"%") && Write(37,16,"%") && Write(37,18,"%") && DrawStatus(); +} + +bool DrawDeathCameraMessage(void) { return Write(0,7,"Let's see that again!"); } + +/* WL_INTER.C Victory: the original eight-floor averages, time and time code. */ +bool DrawVictory(void) +{ + unsigned seconds=0,kill=0,secret=0,treasure=0; + for (unsigned i=0;i<8;++i) { + seconds+=LevelRatios[i].seconds;kill+=LevelRatios[i].kill; + secret+=LevelRatios[i].secret;treasure+=LevelRatios[i].treasure; + } + unsigned minutes=seconds/60;seconds%=60; + if (minutes>99) minutes=seconds=99; + VWB_Bar(0,0,320,160,127); + char time[16];(void)snprintf(time,sizeof(time),"%02u:%02u",minutes,seconds); + if (!Write(18,2,"you win!") || !Write(14,6,"total time") || !Write(12,12,"averages") || + !Write(14,14,"kill %") || !Write(10,16,"secret %") || !Write(6,18,"treasure %") || + !VWB_DrawPic(8,4,L_BJWINSPIC) || !Write(14,8,time) || + !WriteNumber(30,14,kill/8) || !WriteNumber(30,16,secret/8) || + !WriteNumber(30,18,treasure/8)) return false; + if (gamestate.difficulty>=2) { + if (!VWB_DrawPic(240,64,C_TIMECODEPIC)) return false; + char code[4];code[0]=(char)(((minutes/10)^(minutes%10)^10)+'A'); + code[1]=(char)(((seconds/10)^(seconds%10)^10)+'A'); + code[2]=(char)((code[0]^code[1])+'A');code[3]=0; + fontnumber=0;fontcolor=0x47;PrintX=241;PrintY=72; + if (!US_Print(code)) return false; + } + return DrawStatus(); +} + +/* WL_INTER.C LevelCompleted loops and BJ_Breathe, resumed without DOS waits. + Counters run until the original sound wait or 30-VBL boundary. A logical + 140-Hz effect length supplies the wait even with output muted/unavailable. */ +#include "ID_SD.h" +#include "ID_IN.h" +static unsigned breath_frame,breath_max=10; +static struct { + levelratio_t final,shown; + unsigned stage,index,part,breath; + uint64_t until,breath_next; + bool complete,awarded; +} completion; +static bool Breathe(uint64_t ticks) +{ + if(ticks>=completion.breath_next) { + uint64_t steps=1+(ticks-completion.breath_next)/36; + completion.breath_next+=steps*36;breath_frame^=(unsigned)(steps&1U);breath_max=35; + } + completion.breath=breath_frame; + return VWB_DrawPic(0,16,breath_frame?L_GUY2PIC:L_GUYPIC); +} +static bool CompleteResults(uint64_t ticks) +{ + completion.shown=completion.final;completion.complete=true; + completion.breath_next=ticks+breath_max+1; + if(!completion.awarded) { + GivePoints(completion.final.bonus);completion.awarded=true; + if(gamestate.mapon<8) LevelRatios[gamestate.mapon]=completion.final; + } + return DrawLevelCompleted(&completion.final) && VWB_DrawPic(0,16,breath_frame?L_GUY2PIC:L_GUYPIC); +} +static void CountSound(soundnames sound) +{ + GameSound(sound,NULL);completion.until+=SD_SoundTicks(sound); +} +bool LevelIntermissionCounting(void) { return !completion.complete; } +bool StartLevelIntermission(const levelratio_t *stats,uint64_t ticks) +{ + memset(&completion,0,sizeof(completion));completion.final=*stats;completion.shown=*stats; + completion.shown.kill=completion.shown.secret=completion.shown.treasure=0;completion.shown.bonus=0; + completion.until=ticks;completion.breath=breath_frame;completion.breath_next=ticks+breath_max+1; + if(gamestate.mapon>=8) return CompleteResults(ticks); + bool leave=false;return StepLevelIntermission(ticks,false,&leave); +} +bool StepLevelIntermission(uint64_t ticks,bool acknowledge,bool *leave) +{ + *leave=false; + if(acknowledge) { + if(completion.complete) { *leave=true;return true; } + IN_ClearKeysDown();return CompleteResults(ticks); + } + if(completion.complete) return Breathe(ticks); + /* Maximum legitimate WL6 count is bounded by the original map totals. + Run instant iterations together; never invent a frame-rate counter. */ + for(unsigned work=0;work<20000 && !completion.complete && ticks>=completion.until;++work) { + unsigned limit=completion.stage==0 ? (completion.final.seconds=preload.until) { + /* DOS restores the border while black before revealing the level. */ + if(!GameDrawPaused()) return false; + /* Select gameplay geometry while black, before its first fade frame. */ + preload.phase=5;preload.until=ticks+30; + return VL_FadeIn(gamepal,30,ticks); + } + if(preload.phase==5 && ticks>=preload.until) { + ResetPreloadGraphics();IN_ClearKeysDown();GamePauseClock(ticks); + } + return true; +} diff --git a/src/engine/WL_MAIN.c b/src/engine/WL_MAIN.c new file mode 100644 index 00000000..4730026b --- /dev/null +++ b/src/engine/WL_MAIN.c @@ -0,0 +1,531 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_MAIN.C DemoLoop and WL_MENU.C control panel, resumed by monotonic tics. + Title 15s -> credits 10s -> scores 10s -> validated original demo. */ +#include "WL_MAIN.h" +#include "WL_MENU.h" +#include "ID_CA.h" +#include "ID_IN.h" +#include "ID_VH.h" +#include "ID_US_1.h" +#include "WL_DEF.h" +#include "WL_SAVE.h" +#include "ID_SD.h" +#include "WL_CONTROLS.h" +#include "WL_DISPLAY.h" +#include "WL_DEMO.h" +#include "WL_HIGHSCORES.h" +#include +#include +#include +static ui_state state, next_state, signon_return; +static bool leaving; +static bool startup_mouse,startup_synth,startup_digi,allow_debug,debug_unlocked,godmode; +static unsigned jukebox_bank,jukebox_choice; +static char warp_input[3]; +static int jukebox_playing=-1; +void DemoLoopStartupDevices(bool mouse,bool synthesis,bool digitized) +{ startup_mouse=mouse;startup_synth=synthesis;startup_digi=digitized; } +void DemoLoopAllowDebug(bool allow) { allow_debug=allow;debug_unlocked=false; } +bool GameGodMode(void) { return godmode && !Demo_Active(); } +static int score_rank=-1; +static bool score_error; +static uint64_t deadline, transition_end; +static bool resuming; +static uint32_t ui_random=0x574f4c46U; +static const char *QuitMessage(uint64_t ticks) +{ + ui_random^=(uint32_t)ticks;ui_random=ui_random*1664525U+1013904223U; + unsigned first=ui_random>>24;ui_random=ui_random*1664525U+1013904223U; + return MenuQuitMessage(first,ui_random>>24); +} +static unsigned episode,difficulty=2,demo_number; +static ui_state panel_return=UI_MENU,display_return=UI_CONTROLS,quick_return; +static bool boss_music,boss_effects,choosequick,pause_previous; +static int quickslot=-1; +static bool disk_saving,disk_done; +static uint64_t disk_at; +static char disk_name[SAVE_DESCRIPTION]; +static enum { QUICK_END,QUICK_LOAD,QUICK_QUIT,QUICK_NEW,QUICK_ERROR } quick_action; +static bool Attract(void) { return state <= UI_HIGHSCORES || state==UI_DEMO || state==UI_RATING; } +ui_state DemoLoopState(void) { return state; } +void DemoLoopPrepareExit(void) { if(state==UI_BOSS) SD_SetEnabled(boss_music,boss_effects);if(state==UI_PAUSE) SD_SetMusicPaused(pause_previous); } + +static bool GameError(void) +{ + char text[384]="Cannot continue this game:\n",error[256]; + (void)strncpy(error,CA_Error(),sizeof(error)-1);error[sizeof(error)-1]=0; + size_t at=strlen(text);unsigned column=0; + for (const char *p=error;*p && at=34 && *p==' ') { text[at++]='\n';column=0; } + else { text[at++]=*p;++column; } + } + (void)strcpy(text+at,"\nPress a key for menu."); + GameStop();state=UI_ERROR;leaving=false;IN_ClearKeysDown(); + ClearMScreen();return Message(text); +} +static bool ChangeScreen(ui_state screen, uint64_t ticks) +{ + ui_state previous=state; + state = screen; leaving = false; + IN_ClearKeysDown(); + if (screen == UI_DONE) return true; + if(screen==UI_DEMO) { + bool started=false; + for(unsigned n=0;n<4 && !started;++n) started=Demo_Start(demo_number++%4,ticks+30); + if(!started) { GameStop();return ChangeScreen(UI_TITLE,ticks); } + } + if(screen==UI_VIEW && !BeginViewMenu()) return false; + if(screen==UI_BOSS) { + unsigned music,effects;SD_GetSettings(&music,&effects,&boss_music,&boss_effects); + SD_SetEnabled(false,boss_effects);VWB_Bar(0,0,320,200,0); + fontnumber=0;fontcolor=15;PrintX=WindowX=PrintY=0;if(!US_Print("C>")) return false; + } + if (screen == UI_GAME) { + bool ok; + if(resuming) { GamePauseClock(ticks+10);ok=GameDrawPaused();resuming=false; + sd_status audio;SD_GetStatus(&audio);int song=SD_LevelMusic((unsigned)gamestate.episode,(unsigned)gamestate.mapon); + if(audio.music!=song) SD_StartMusic(song); } + else ok=GameStartSelected(ticks+10,episode,difficulty); + if(!ok) return GameError() && VL_FadeIn(gamepal,10,ticks); + if(GamePreloadPending()) return StartPreloadGraphics(ticks) || GameError(); + } + if ((screen==UI_SAVE || screen==UI_LOAD) && !BeginSaveMenu(screen==UI_SAVE)) return false; + if (screen == UI_TITLE || (screen==UI_RATING && previous==UI_SIGNON)) SD_StartMusic(7); + if (screen == UI_MENU) SD_StartMusic(14); + if (screen == UI_SCORES || screen == UI_HIGHSCORES || screen==UI_RESULTS) SD_StartMusic(23); + if(screen==UI_RESULTS) { + score_error=false; + if(score_rank>=0) { if(!BeginHighScoreEntry(score_rank,ticks+30)) return false; } + else if(!DrawHighScores()) return false; + } + if(screen==UI_CONTROLS || screen==UI_SOUND || screen==UI_SAVE || screen==UI_LOAD) ResetMenuCursor(ticks); + if(screen==UI_DISPLAY && !BeginDisplayMenu()) return false; + if(screen==UI_CONTROLS && !(previous==UI_DISPLAY?ResumeControlsMenu():BeginControlsMenu())) return false; + if (screen == UI_SOUND && !BeginSoundSettings()) return false; + if (screen == UI_TITLE && !CA_CacheScreen(TITLEPIC)) return false; + if(screen==UI_RATING) { + VWB_Bar(0,0,320,200,0x82); + if(!VWB_DrawPic(216,110,PG13PIC)) return false; + } + if (screen == UI_CREDITS && !CA_CacheScreen(CREDITSPIC)) return false; + if ((screen == UI_HIGHSCORES || screen == UI_SCORES) && !DrawHighScores()) return false; + if (screen == UI_MENU && !SetupControlPanel(ticks)) return false; + if (screen == UI_EPISODE && !DrawNewSelection(true,episode)) return false; + if (screen == UI_DIFFICULTY && !DrawNewSelection(false,difficulty)) return false; + unsigned steps = Attract() || screen==UI_RESULTS ? 30 : 10; + if (!VL_FadeIn(gamepal,steps,ticks)) return false; + deadline = ticks + steps + (screen==UI_RATING?7U*70U:screen == UI_TITLE ? 15U*70U : 10U*70U); + if(screen==UI_RESULTS) deadline=ticks+30+500; + return true; +} +static bool Transition(ui_state next, uint64_t ticks, unsigned steps) +{ + leaving = true; next_state = next; transition_end = ticks + steps; + IN_ClearKeysDown(); + /* CP_Quit/CP_CheckQuick silence both streams before MenuFadeOut. */ + if(next==UI_DONE) { SD_StartMusic(-1);SD_StopSound(); } + /* MenuFadeOut is dark red, VW_FadeOut is black. */ + return VL_FadeOut(Attract() || state==UI_SIGNON || state==UI_RESULTS || next==UI_RESULTS ? 0 : 43,0,0,steps,ticks); +} +bool DemoLoopStartGame(uint64_t ticks) { quickslot=-1;episode=0;difficulty=2;resuming=false;return ChangeScreen(UI_GAME,ticks); } +bool DemoLoopStartup(uint64_t ticks, bool menu) +{ + GameStop();resuming=false;quickslot=-1;demo_number=0;panel_return=UI_MENU;choosequick=false; + /* Validate the complete UI slice before starting the event loop. */ + if (!VW_ValidateFont(0) || !VW_ValidateFont(1) || !DrawHighScores() || + !SetupControlPanel(ticks) || !CA_CacheScreen(CREDITSPIC) || !CA_CacheScreen(TITLEPIC)) return false; + if (!VL_FadeOut(0,0,0,0,ticks)) return false; + return ChangeScreen(menu ? UI_MENU : UI_TITLE,ticks); +} +/* FinishSignon uses the normal font, centred at y=190. Leave the original + memory/card indicators unfilled: DOS resources are not modern measurements. */ +static bool SignonPrompt(const char *text,w3r_byte color) +{ + int old_font=fontnumber,old_x=px,old_y=py,width,height; + w3r_byte old_color=fontcolor; + fontnumber=0;fontcolor=color; + bool ok=VW_MeasurePropString(text,&width,&height); + if(ok) { + VWB_Bar(0,189,300,11,framebuffer[0]); + px=(320-width)/2;py=190;ok=VW_DrawPropString(text); + } + fontnumber=old_font;fontcolor=old_color;px=old_x;py=old_y;return ok; +} +bool DemoLoopSignon(const char *path,uint64_t ticks) +{ + /* Original DOS introscn was linked into the executable, not WL6. + A user-supplied 320x200 raw indexed image can restore its appearance. + Never synthesize DOS hardware detection data. */ + if(!path || GameRunning() || (state!=UI_TITLE && state!=UI_RATING)) return true; + FILE *file=fopen(path,"rb"); + if(!file) return errno==ENOENT ? true : CA_Fail("Cannot open optional SIGNON.RAW"); + unsigned char pixels[320U*200U]; + size_t count=fread(pixels,1,sizeof(pixels),file); + int extra=fgetc(file),read_error=ferror(file); + if(fclose(file)!=0) read_error=1; + if(read_error || count!=sizeof(pixels) || extra!=EOF) + return CA_Fail("Sign-on image must contain exactly 64000 indexed pixels"); + signon_return=state; + memcpy(framebuffer,pixels,sizeof(pixels)); + /* WL_MENU.C IntroScreen hardware boxes: fill supported virtual devices + at the original coordinates. No conventional/EMS/XMS inventory exists. */ + if(startup_mouse) VWB_Bar(164,82,12,2,14); + if(startup_synth && !startup_digi) VWB_Bar(164,128,12,2,14); + if(startup_digi) VWB_Bar(164,151,12,2,14); + if(!SignonPrompt("Press a key",14)) return false; + state=UI_SIGNON;leaving=false;IN_ClearKeysDown(); + SD_StartMusic(-1); + return VL_FadeIn(gamepal,10,ticks); +} +bool DemoLoopIntro(uint64_t ticks) +{ + /* WL_INTER.C PG13: the sign-on image linked into DOS is a different asset. + Never fabricate it or mistake a setup-program screen for archive art. */ + if(!CA_GrChunkPresent(PG13PIC) || pictable[PG13PIC-STARTPICS].width!=88 || + pictable[PG13PIC-STARTPICS].height!=64) return true; + if(state!=UI_TITLE || GameRunning()) return true; + return ChangeScreen(UI_RATING,ticks); +} +static bool ReturnPanel(uint64_t ticks) +{ + resuming=panel_return==UI_GAME;return Transition(panel_return,ticks,10); +} +static bool QuickDialog(int action,uint64_t ticks) +{ + quick_action=action;if(state!=UI_QUICK) quick_return=state;FinishPaletteShifts(); + if(GameRunning() && state==UI_GAME && !GameDrawPaused()) return false; + state=UI_QUICK;IN_ClearKeysDown(); + const char *text=action==QUICK_END?"Are you sure you want\nto end the game you\nare playing? (Y or N):": + action==QUICK_QUIT?QuitMessage(ticks): + action==QUICK_NEW?"You are currently in\na game. Continuing will\nerase old game. Ok?": + action==QUICK_ERROR?"Quick operation failed.\nPress a key to return.":NULL; + if(!text) { + save_info info;Save_ReadInfo((unsigned)quickslot,&info); + char message[128];(void)snprintf(message,sizeof(message),"Load Game called\n\"%s\"? (Y/N)",info.description); + return BeginConfirmationAtHeight(message,ticks,quick_return==UI_GAME?160U:200U); + } + return action==QUICK_ERROR?MessageAtHeight(text,quick_return==UI_GAME?160U:200U):BeginConfirmationAtHeight(text,ticks,quick_return==UI_GAME?160U:200U); +} +static bool QuickActivity(bool saving,const char *name,uint64_t ticks) +{ + disk_saving=saving;disk_done=false;disk_at=ticks+1; + (void)snprintf(disk_name,sizeof(disk_name),"%s",name?name:""); + state=UI_DISK;IN_ClearKeysDown();return DrawSaveActivity(saving,false); +} +static bool QuickSave(uint64_t ticks) +{ + save_info info;if(quickslot>=0) { quickslot=(int)SaveMenuSelected();Save_ReadInfo((unsigned)quickslot,&info); } + if(quickslot<0 || info.status!=SAVE_VALID) { + quickslot=-1;choosequick=true;panel_return=UI_GAME;return Transition(UI_SAVE,ticks,10); + } + IN_ClearKeysDown();GamePauseClock(ticks); + return QuickActivity(true,info.description,ticks); +} +static bool GameMessage(const char *text) +{ + FinishPaletteShifts();if(!GameDrawPaused() || !MessageAtHeight(text,160)) return false; + state=UI_MESSAGE;IN_ClearKeysDown();return true; +} +/* WL_MAIN.C DoJukebox: registered WL6 has three time-selected six-song banks. */ +static const unsigned jukebox_tracks[]={3,11,9,12,2,0,8,18,17,4,1,19,6,20,22,21,19,26}; +static const char *const jukebox_names[]={ + "Get Them!","Searching","P.O.W.","Suspense","War March","Around The Corner!", + "Nazi Anthem","Lurking...","Going After Hitler","Pounding Headache","Into the Dungeons","Ultimate Conquest", + "Kill the S.O.B.","The Nazi Rap","Twelfth Hour","Zero Hour","Ultimate Conquest","Wolfpack" +}; +static bool DrawJukebox(void) +{ + ClearMScreen();DrawStripes(10);DrawWindow(22,64,280,91,BKGDCOLOR); + if(!VWB_DrawPic(112,184,C_MOUSELBACKPIC)) return false; + fontnumber=1;fontcolor=0x47;int w,h; + if(!VW_MeasurePropString("Robert's Jukebox",&w,&h)) return false; + PrintX=(320-w)/2;PrintY=15;if(!US_Print("Robert's Jukebox")) return false; + for(unsigned i=0;i<6;++i) { + fontcolor=i==jukebox_choice?HIGHLIGHT:(int)i==jukebox_playing?0x4a:TEXTCOLOR; + PrintX=56;PrintY=70+(int)i*13;if(!US_Print(jukebox_names[jukebox_bank*6+i])) return false; + } + return VWB_DrawPic(24,68+(int)jukebox_choice*13,MenuCursorPicture()); +} +bool DemoLoopJukebox(uint64_t ticks,unsigned bank) +{ + if(GameRunning() || bank>2) return CA_Fail("Jukebox unavailable"); + jukebox_bank=bank;jukebox_choice=0;jukebox_playing=-1; + state=UI_JUKEBOX;leaving=false;ResetMenuCursor(ticks);IN_ClearKeysDown(); + return DrawJukebox() && VL_FadeIn(gamepal,10,ticks); +} +static bool HiddenKeys(uint64_t ticks,bool *handled) +{ + *handled=true; + if(Keyboard[0x32] && Keyboard[0x26] && Keyboard[0x17]) { + /* WL_PLAY.C MLI: score reset and ten-minute time penalty are vital. */ + gamestate.health=100;gamestate.ammo=99;gamestate.keys=3;gamestate.score=0; + gamestate.TimeCount+=42000U;GiveWeapon(wp_chaingun); + return GameMessage("You now have 100% Health,\n99 Ammo and both Keys!\n\nNote that you have basically\neliminated your chances of\ngetting a high score!"); + } + if(allow_debug && Keyboard[0x0e] && Keyboard[0x2a] && Keyboard[0x38]) { + debug_unlocked=true;return GameMessage("Debugging keys are\nnow available!"); + } + if(Keyboard[0x30] && Keyboard[0x1e] && Keyboard[0x14]) + return GameMessage("Commander Keen is also\navailable from Apogee, but\nthen, you already know\nthat - right, Cheatmeister?!"); + if(debug_unlocked && Keyboard[0x0f]) { + char text[160]; + if(Keyboard[0x22]) { godmode=!godmode;return GameMessage(godmode?"God mode ON":"God mode OFF"); } + if(Keyboard[0x23]) { IN_ClearKeysDown();TakeDamage(16,NULL);return true; } + if(Keyboard[0x17]) { + GivePoints(100000);HealSelf(99);if(gamestate.bestweaponnext) { if(ob->active) ++active;else ++inactive; } + for(unsigned i=0;i=deadline)) { + if(!Transition(UI_TITLE,ticks>=deadline?deadline:ticks,30)) return false; + continue; + } + if (Attract() && IN_AnyPressed()) { if(state==UI_DEMO) GameStop();return Transition(UI_MENU,ticks,30); } + if (Attract() && state!=UI_DEMO && ticks >= deadline) { + ui_state next = state == UI_TITLE ? UI_CREDITS : state == UI_CREDITS ? UI_HIGHSCORES : UI_DEMO; + if (!Transition(next,deadline,30)) return false; + continue; + } + break; + } + if(state==UI_GAME && GameLoading()) return StepPreloadGraphics(ticks) || GameError(); + if(VL_Fading()) return true; + if(state==UI_DEMO) { + if(!GameStep(ticks) || Demo_Finished()) { GameStop();return Transition(UI_TITLE,ticks,30); } + return true; + } + if(state==UI_SIGNON || Attract()) return true; + if((state==UI_CONTROLS || state==UI_SOUND || state==UI_SAVE || state==UI_LOAD) && TickMenuCursor(ticks)) { + if(state==UI_CONTROLS && !DrawControlsMenu()) return false; + if(state==UI_SOUND && !DrawSoundSettings()) return false; + } + if((state==UI_MENU || state==UI_SOUND || state==UI_CONTROLS || state==UI_DISPLAY || state==UI_VIEW || state==UI_EPISODE || state==UI_DIFFICULTY) && IN_ConsumePress(sc_Pause)) + SD_SetMusicPaused(!SD_MusicPaused()); + if (state == UI_GAME) { + if(GamePreloadPending()) return StartPreloadGraphics(ticks) || GameError(); + /* DOS US_ControlPanel/CP_CheckQuick: panel entry freezes gameplay, + direct F-key panels return to the game, not the main menu. */ + if(GameCanSave()) { + bool handled;if(!HiddenKeys(ticks,&handled)) return false;if(handled) return true; + } + if(GameCanSave() && IN_ConsumePress(sc_Pause)) { + FinishPaletteShifts(); + if(!GameDrawPaused() || !VWB_DrawPic(128,64,PAUSEDPIC)) return false; + pause_previous=SD_MusicPaused();SD_SetMusicPaused(true); + IN_ClearKeysDown();state=UI_PAUSE;return true; + } + if(GameCanSave()) { + panel_return=UI_GAME;choosequick=false; + if(IN_ConsumePress(0x3b)) { FinishPaletteShifts();return Transition(UI_BOSS,ticks,10); } + if(IN_ConsumePress(0x3c) && *Save_Directory()) { FinishPaletteShifts();return Transition(UI_SAVE,ticks,10); } + if(IN_ConsumePress(0x3d) && *Save_Directory()) { FinishPaletteShifts();return Transition(UI_LOAD,ticks,10); } + if(IN_ConsumePress(0x3e)) { FinishPaletteShifts();return Transition(UI_SOUND,ticks,10); } + if(IN_ConsumePress(0x3f)) { FinishPaletteShifts();return Transition(UI_VIEW,ticks,10); } + if(IN_ConsumePress(0x40)) { FinishPaletteShifts();return Transition(UI_CONTROLS,ticks,10); } + if(IN_ConsumePress(0x41)) return QuickDialog(QUICK_END,ticks); + if(IN_ConsumePress(0x42) && *Save_Directory()) return QuickSave(ticks); + if(IN_ConsumePress(0x43) && *Save_Directory()) { + save_info info;if(quickslot>=0) { quickslot=(int)SaveMenuSelected();Save_ReadInfo((unsigned)quickslot,&info); } + if(quickslot>=0 && info.status==SAVE_VALID) return QuickDialog(QUICK_LOAD,ticks); + quickslot=-1;choosequick=true;return Transition(UI_LOAD,ticks,10); + } + if(IN_ConsumePress(0x44)) return QuickDialog(QUICK_QUIT,ticks); + } + if (GameCanSave() && (CT_Pressed(CT_MENU) || IN_ConsumePress(sc_Escape))) { FinishPaletteShifts();return Transition(UI_MENU,ticks,10); } + if (!GameStep(ticks)) return GameError(); + if(GamePreloadPending()) return StartPreloadGraphics(ticks) || GameError(); + if (GameFinished()) { + score_rank=HighScores_Insert((uint32_t)gamestate.score,(unsigned)gamestate.mapon+1,(unsigned)gamestate.episode); + GameStop();return Transition(UI_RESULTS,ticks,30); + } + return true; + } + if (state == UI_MENU) { + panel_return=UI_MENU;choosequick=false; + if(IN_ConsumePress(0x3b)) return Transition(UI_BOSS,ticks,10); + int action = HandleMenu(ticks); + if (action == -3) return false; + if (action == savegame || action == loadgame) return Transition(action==savegame?UI_SAVE:UI_LOAD,ticks,10); + if (action == changeview) return Transition(UI_VIEW,ticks,10); + if (action == control) return Transition(UI_CONTROLS,ticks,10); + if (action == soundmenu) return Transition(UI_SOUND,ticks,10); + if (action == newgame) return Transition(UI_EPISODE,ticks,10); + if (action == viewscores) return GameRunning()?QuickDialog(QUICK_END,ticks):Transition(UI_SCORES,ticks,10); + if (action == backtodemo) { resuming=GameRunning();return Transition(resuming?UI_GAME:UI_TITLE,ticks,10); } + if (action == quit || action == -1) { + state = UI_CONFIRM; + return BeginConfirmation(QuitMessage(ticks),ticks); + } + } else if (state==UI_SAVE || state==UI_LOAD) { + int action=HandleSaveMenu(ticks); + if(action==-3) return false; + if(action==-1 || action==1) { + bool loaded=action==1 && state==UI_LOAD; + if(action==1 && choosequick) quickslot=(int)SaveMenuSelected(); + choosequick=false; + if(loaded) { resuming=true;return Transition(UI_GAME,ticks,10); } + return ReturnPanel(ticks); + } + } else if(state==UI_DISPLAY) { + int action=HandleDisplayMenu();if(action==-3) return false; + if(action==-1) return Transition(display_return,ticks,10); + } else if(state==UI_CONTROLS) { + int action=HandleControlsMenu();if(action==-3) return false; + if(action==2) { display_return=UI_CONTROLS;return Transition(UI_DISPLAY,ticks,10); } + if(action==-1) return ReturnPanel(ticks); + } else if(state==UI_VIEW) { + int action=HandleViewMenu(ticks);if(action==-3) return false; + if(action==-1 || action==1) return ReturnPanel(ticks); + } else if(state==UI_BOSS) { + if(IN_ConsumePress(sc_Escape)) { SD_SetEnabled(boss_music,boss_effects);return ReturnPanel(ticks); } + } else if(state==UI_QUICK) { + int answer=quick_action==QUICK_ERROR?(IN_AnyPressed()?-1:0):HandleConfirmation(ticks); + if(answer==-3) return false; + if(answer) { + bool yes=answer>0; + if(yes && quick_action==QUICK_QUIT) return Transition(UI_DONE,ticks,10); + if(quick_action==QUICK_NEW) return Transition(yes?UI_DIFFICULTY:UI_MENU,ticks,10); + if(yes && quick_action==QUICK_END) { + /* CP_EndGame returns ex_died with zero lives to GameLoop. */ + gamestate.lives=0;gamestate.died=true;killerobj=NULL; + quickslot=-1;resuming=true;return Transition(UI_GAME,ticks,10); + } + if(yes && quick_action==QUICK_LOAD) return QuickActivity(false,NULL,ticks); + resuming=quick_return==UI_GAME;return Transition(quick_return,ticks,10); + } + } else if(state==UI_DISK) { + if(ticks=1 && floor<=10) { if(!GameWarp(ticks,floor)) return GameError(); } + else { IN_ClearKeysDown();GamePauseClock(ticks); } + state=UI_GAME; + if(GamePreloadPending()) return StartPreloadGraphics(ticks) || GameError(); + return GameDrawPaused(); + } + size_t n=strlen(warp_input);bool redraw=false; + if(IN_ConsumePress(0x0e) && n) { warp_input[--n]=0;redraw=true; } + char ch;while((ch=IN_NextASCII())!=0) if(ch>='0' && ch<='9' && n<2) { warp_input[n++]=ch;warp_input[n]=0;redraw=true; } + if(redraw) { + char prompt[80];(void)snprintf(prompt,sizeof(prompt),"Warp to which level(1-10):\n%s",warp_input); + if(!GameDrawPaused() || !MessageAtHeight(prompt,160)) return false; + } + } else if(state==UI_MESSAGE) { + if(IN_AnyPressed()) { IN_ClearKeysDown();GamePauseClock(ticks);state=UI_GAME;return GameDrawPaused(); } + } else if(state==UI_PAUSE) { + if(IN_AnyPressed()) { + SD_SetMusicPaused(pause_previous);IN_ClearKeysDown(); + GamePauseClock(ticks);state=UI_GAME;return GameDrawPaused(); + } + } else if (state == UI_SOUND) { + int action=HandleSoundSettings(); + if(action==-3) return false; + if(action==-1) return ReturnPanel(ticks); + } else if (state == UI_EPISODE || state == UI_DIFFICULTY) { + bool choosing_episode=state==UI_EPISODE; + int action=HandleNewSelection(ticks,choosing_episode,choosing_episode ? &episode : &difficulty); + if (action==-3) return false; + if (action==-1) return Transition(choosing_episode ? UI_MENU : UI_EPISODE,ticks,10); + if(action==1 && choosing_episode && GameRunning()) return QuickDialog(QUICK_NEW,ticks); + if(action==1 && !choosing_episode) quickslot=-1; + if (action==1) return Transition(choosing_episode ? UI_DIFFICULTY : UI_GAME,ticks,10); + } else if(state==UI_RESULTS) { + if(score_error) { if(IN_AnyPressed()) return Transition(UI_TITLE,ticks,30); } + else if(score_rank>=0) { + int result=HandleHighScoreEntry(ticks);if(result<0) return false; + if(result) { + score_rank=-1; + if(!HighScores_Save()) { + score_error=true;IN_ClearKeysDown(); + return Message("Cannot save high scores.\nRanking retained this session.\nPress a key to continue."); + } + return Transition(UI_TITLE,ticks,30); + } + } else if(IN_AnyPressed() || ticks>=deadline) return Transition(UI_TITLE,ticks,30); + } else if (state == UI_ERROR && IN_AnyPressed()) { + return Transition(UI_MENU,ticks,10); + } else if (state == UI_SCORES && IN_AnyPressed()) { + return Transition(UI_MENU,ticks,10); + } else if (state == UI_CONFIRM) { + int answer=HandleConfirmation(ticks); + if(answer==-3) return false; + if(answer>0) return Transition(UI_DONE,ticks,10); + if(answer<0) { + state=UI_MENU; + if(!SetupControlPanel(ticks)) return false; + } + } + IN_ClearPressed();CT_EndTic(); + return true; +} + +bool DemoLoop(uint64_t ticks) +{ + bool ok=StepDemoLoop(ticks); + CT_SetGameplay(ok && state==UI_GAME && GameCanSave() && !VL_Fading()); + return ok; +} diff --git a/src/engine/WL_MAIN.h b/src/engine/WL_MAIN.h new file mode 100644 index 00000000..a478becb --- /dev/null +++ b/src/engine/WL_MAIN.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_MAIN_H +#define WL_MAIN_H +#include +#include +typedef enum { UI_TITLE, UI_CREDITS, UI_HIGHSCORES, UI_MENU, UI_SCORES, UI_CONFIRM, UI_GAME, UI_EPISODE, UI_DIFFICULTY, UI_ERROR, UI_SOUND, UI_SAVE, UI_LOAD, UI_CONTROLS, UI_DISPLAY, UI_VIEW, UI_BOSS, UI_DEMO, UI_QUICK, UI_DONE, UI_RATING, UI_SIGNON, UI_PAUSE, UI_RESULTS, UI_MESSAGE, UI_JUKEBOX, UI_DISK, UI_WARP } ui_state; +/* Runtime equivalents of DOS capability lights; no invented EMS/XMS counts. */ +void DemoLoopStartupDevices(bool mouse,bool synthesis,bool digitized); +bool DemoLoopJukebox(uint64_t ticks,unsigned bank); +void DemoLoopAllowDebug(bool allow); +bool GameGodMode(void); +bool DemoLoopStartup(uint64_t ticks, bool menu); +/* Optional verified archive PG13 picture; normal title/menu API stays unchanged. */ +bool DemoLoopIntro(uint64_t ticks); +/* Optional headerless 320x200 row-major image using gamepal. Call after + Startup/Intro for normal startup only; missing art leaves that state intact. + Malformed/unreadable art fails before replacing the framebuffer. */ +bool DemoLoopSignon(const char *path,uint64_t ticks); +bool DemoLoop(uint64_t ticks); +ui_state DemoLoopState(void); +void DemoLoopPrepareExit(void); +bool DemoLoopStartGame(uint64_t ticks); +#endif diff --git a/src/engine/WL_MENU.c b/src/engine/WL_MENU.c new file mode 100644 index 00000000..2f752a29 --- /dev/null +++ b/src/engine/WL_MENU.c @@ -0,0 +1,342 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_MENU.C by John Romero (C) 1992 Id Software, Inc. + GOODTIMES control-panel slice; blocking HandleMenu is now tic-driven. + Gameplay-dependent rows retain original disabled rendering and are skipped. */ +#include "WL_MENU.h" +#include "WL_SAVE.h" +#include "WL_DISPLAY.h" +#include "ID_CA.h" +#include "ID_VH.h" +#include "ID_US_1.h" +#include "ID_IN.h" +#include "ID_SD.h" +#include +#include +#include +CP_iteminfo MainItems = {76, 55, MENU_COUNT, viewscores, 24}; +CP_itemtype MainMenu[MENU_COUNT] = { + {0,"New Game"}, {0,"Sound"}, {1,"Control"}, {0,"Load Game"}, {0,"Save Game"}, + {1,"Change View"}, {1,"View Scores"}, {1,"Back to Demo"}, {1,"Quit"} +}; +static int shape = C_CURSOR1PIC; +static uint64_t gun_next, move_next,menu_time,navigation_next; +static bool gun_first; +int MenuCursorPicture(void) { return shape; } +void MenuCursorMoved(void) { shape=C_CURSOR1PIC; } +void ResetMenuCursor(uint64_t ticks) +{ shape=C_CURSOR1PIC;gun_first=true;gun_next=ticks+9;menu_time=navigation_next=ticks; } +int MenuNavigation(void) +{ + bool up=IN_ConsumePress(sc_UpArrow),down=IN_ConsumePress(sc_DownArrow); + bool held=Keyboard[sc_UpArrow] || Keyboard[sc_DownArrow]; + if(!held) navigation_next=menu_time; + if(up || down || (held && menu_time>=navigation_next)) { + navigation_next=menu_time+20; + return up || (!down && Keyboard[sc_UpArrow])?-1:1; + } + return 0; +} +bool TickMenuCursor(uint64_t ticks) +{ + menu_time=ticks; + if (ticks >= gun_next) { + /* Original first 8-tic blink, then alternate 8/70-tic intervals. */ + if (gun_first) { shape = C_CURSOR2PIC; gun_next += 9; gun_first = false; } + if (ticks >= gun_next) gun_next += ((ticks-gun_next)/80)*80; + while (ticks >= gun_next) { + if (shape == C_CURSOR2PIC) { shape = C_CURSOR1PIC; gun_next += 71; } + else { shape = C_CURSOR2PIC; gun_next += 9; } + } + return true; + } + return false; +} +void ClearMScreen(void) { VWB_Bar(0, 0, 320, 200, BORDCOLOR); } +void DrawStripes(int y) { VWB_Bar(0, y, 320, 24, 0); VWB_Hlin(0, 319, y + 22, STRIPE); } +static void DrawOutline(int x, int y, int w, int h, w3r_byte color1, w3r_byte color2) +{ + VWB_Hlin(x,x+w,y,color2); VWB_Vlin(y,y+h,x,color2); + VWB_Hlin(x,x+w,y+h,color1); VWB_Vlin(y,y+h,x+w,color1); +} +void DrawWindow(int x, int y, int w, int h, w3r_byte color) +{ + VWB_Bar(x,y,w,h,color); DrawOutline(x,y,w,h,BORD2COLOR,DEACTIVE); +} +bool DrawMainMenu(void) +{ + ClearMScreen(); + if (!VWB_DrawPic(112,184,C_MOUSELBACKPIC)) return false; + DrawStripes(10); + if (!VWB_DrawPic(84,0,C_OPTIONSPIC)) return false; + DrawWindow(68,52,178,13*10+6,BKGDCOLOR); + fontnumber = 1; WindowX = 100; + for (int i = 0; i < MENU_COUNT; ++i) { + fontcolor = MainMenu[i].active ? (i == MainItems.curpos ? HIGHLIGHT : TEXTCOLOR) : DEACTIVE; + PrintX = 100; PrintY = 55 + i * 13; + if (!US_Print(MainMenu[i].string)) return false; + } + return VWB_DrawPic(72,53 + MainItems.curpos * 13,shape); +} +bool SetupControlPanel(uint64_t ticks) +{ + if (!VW_ValidateFont(1)) return false; + MainMenu[changeview].active=1; + MainMenu[loadgame].active=*Save_Directory()?1:0; + MainMenu[savegame].active=GameCanSave() && *Save_Directory()?1:0; + MainMenu[viewscores].string=GameRunning()?"End Game":"View Scores"; + MainMenu[backtodemo].string=GameRunning()?"Back to Game":"Back to Demo"; + if (MainItems.curpos < 0 || MainItems.curpos >= MENU_COUNT || !MainMenu[MainItems.curpos].active) MainItems.curpos = viewscores; + ResetMenuCursor(ticks);move_next=ticks; + return DrawMainMenu(); +} +static void MoveGun(int direction) +{ + do { MainItems.curpos = (MainItems.curpos + direction + MENU_COUNT) % MENU_COUNT; } + while (!MainMenu[MainItems.curpos].active); + shape = C_CURSOR1PIC; + (void)SD_PlaySound(MOVEGUN1SND,0,0); +} +int HandleMenu(uint64_t ticks) +{ + bool redraw = false; + bool up = IN_ConsumePress(sc_UpArrow), down = IN_ConsumePress(sc_DownArrow); + if (up || down || ((Keyboard[sc_UpArrow] || Keyboard[sc_DownArrow]) && ticks >= move_next)) { + int direction = (up || (!down && Keyboard[sc_UpArrow])) ? -1 : 1; + uint64_t moves = up || down ? 1 : (ticks - move_next) / 20 + 1; + unsigned available = 0; + for (int i = 0; i < MENU_COUNT; ++i) if (MainMenu[i].active) ++available; + /* Repeated cycles return to the same selection; avoid catch-up loops. */ + for (uint64_t n = 0; n < moves % available; ++n) MoveGun(direction); + move_next = up || down ? ticks + 20 : move_next + moves * 20; + redraw = true; + } + if (!Keyboard[sc_UpArrow] && !Keyboard[sc_DownArrow]) move_next = ticks; + char ascii; + while ((ascii=IN_NextASCII()) != 0) { + int key = toupper((unsigned char)ascii); + for (int offset = 1; offset <= MENU_COUNT; ++offset) { + int item = (MainItems.curpos + offset) % MENU_COUNT; + if (MainMenu[item].active && MainMenu[item].string[0] == key) { + MainItems.curpos = item; shape = C_CURSOR1PIC; redraw = true; break; + } + } + } + if(TickMenuCursor(ticks)) redraw=true; + if (redraw && !DrawMainMenu()) return -3; + bool escape=IN_ConsumePress(sc_Escape); + bool enter=IN_ConsumePress(sc_Enter), space=IN_ConsumePress(sc_Space); + if (escape) { (void)SD_PlaySound(ESCPRESSEDSND,0,0);return -1; } + if (enter || space) { (void)SD_PlaySound(SHOOTSND,0,0);return MainItems.curpos; } + return -2; +} +bool Message(const char *text) { return MessageAtHeight(text,200); } +bool MessageAtHeight(const char *text,unsigned area_height) +{ + char line[256]; + int width = 0, height = 0, line_height = 0; + fontnumber = 1; + const char *p = text; + for (;;) { + const char *end = strchr(p,'\n'); size_t size = end ? (size_t)(end-p) : strlen(p); + int w; + if (size >= sizeof(line)) return CA_Fail("Dialog line too long"); + memcpy(line,p,size); line[size]=0; + if (!VW_MeasurePropString(line,&w,&line_height)) return false; + height += line_height; + /* Preserve Message's original final-line padding rule. */ + if(!end) { if(w+10>width) width=w+10;break; } + if(w>width) width=w; + p = end+1; + } + PrintY = (int)(area_height/2) - height/2; PrintX = WindowX = 160-width/2; + DrawWindow(WindowX-5,PrintY-5,width+10,height+10,TEXTCOLOR); + DrawOutline(WindowX-5,PrintY-5,width+10,height+10,0,HIGHLIGHT); + fontcolor = 0; + return US_Print(text); +} + +/* WL_MENU.C DrawNewEpisode/DrawNewGame. Both use the same input queue as + the control panel; a selection clears edges before entering the next page. */ +bool DrawNewSelection(bool episode,unsigned choice) +{ + static const char *episodes[]={"Escape from Wolfenstein","Operation: Eisenfaust","Die, Fuhrer, Die!","A Dark Secret","Trail of the Madman","Confrontation"}; + static const char *skills[]={"Can I play, Daddy?","Don't hurt me.","Bring 'em on!","I am Death incarnate!"}; + ClearMScreen(); + if (!VWB_DrawPic(112,184,C_MOUSELBACKPIC)) return false; + fontnumber=1;fontcolor=TEXTCOLOR; + if (episode) { + DrawWindow(6,19,308,162,BKGDCOLOR); + PrintX=72;PrintY=2;if (!US_Print("Which episode to play?")) return false; + for (unsigned i=0;i<6;++i) { + if (!VWB_DrawPic(42,23+(int)i*26,C_EPISODE1PIC+(int)i)) return false; + fontcolor=i==choice ? HIGHLIGHT : TEXTCOLOR; + char label[80];(void)snprintf(label,sizeof(label),"Episode %u\n%s",i+1,episodes[i]); + PrintX=98;PrintY=23+(int)i*26;if (!US_Print(label)) return false; + } + return VWB_DrawPic(10,24+(int)choice*26,C_CURSOR1PIC); + } + PrintX=70;PrintY=68;if (!US_Print("How tough are you?")) return false; + DrawWindow(45,90,225,67,BKGDCOLOR); + for (unsigned i=0;i<4;++i) { + fontcolor=i==choice ? HIGHLIGHT : TEXTCOLOR; + PrintX=74;PrintY=100+(int)i*13;if (!US_Print(skills[i])) return false; + } + return VWB_DrawPic(50,98+(int)choice*13,C_CURSOR1PIC) && + VWB_DrawPic(235,107,C_BABYMODEPIC+(int)choice); +} +int HandleNewSelection(uint64_t ticks,bool episode,unsigned *choice) +{ + unsigned count=episode ? 6U : 4U; + bool up=IN_ConsumePress(sc_UpArrow),down=IN_ConsumePress(sc_DownArrow); + if (up || down || ((Keyboard[sc_UpArrow] || Keyboard[sc_DownArrow]) && ticks>=move_next)) { + *choice=(*choice+((up || (!down && Keyboard[sc_UpArrow])) ? count-1 : 1))%count; + move_next=ticks+20; + (void)SD_PlaySound(MOVEGUN1SND,0,0); + if (!DrawNewSelection(episode,*choice)) return -3; + } + bool escape=IN_ConsumePress(sc_Escape),enter=IN_ConsumePress(sc_Enter),space=IN_ConsumePress(sc_Space); + if (escape) { (void)SD_PlaySound(ESCPRESSEDSND,0,0);return -1; } + if (enter || space) { (void)SD_PlaySound(SHOOTSND,0,0);return 1; } + return 0; +} + +/* Original DrawSoundMenu panels and graphics; Revive exposes supported + synthesis/effects settings, not obsolete physical-device selections. */ +static unsigned sound_choice,volume_choice; +static bool volume_page; +bool DrawSoundSettings(void) +{ + unsigned music,effects;bool mon,eon;SD_GetSettings(&music,&effects,&mon,&eon); + ClearMScreen();fontnumber=1;fontcolor=TEXTCOLOR; + if(!VWB_DrawPic(112,184,C_MOUSELBACKPIC)) return false; + if(volume_page) { + DrawStripes(10);DrawWindow(40,65,240,80,BKGDCOLOR); + int w,h;if(!VW_MeasurePropString("Volume",&w,&h)) return false; + PrintX=(320-w)/2;PrintY=14;if(!US_Print("Volume")) return false; + for(unsigned i=0;i<2;++i) { + char text[48];(void)snprintf(text,sizeof(text),"%s: %u%%",i?"Effects":"Music",i?effects:music); + fontcolor=i==volume_choice?HIGHLIGHT:TEXTCOLOR;PrintX=80;PrintY=80+(int)i*26; + if(!US_Print(text)) return false; + } + return VWB_DrawPic(48,78+(int)volume_choice*26,MenuCursorPicture()); + } + DrawWindow(40,17,250,45,BKGDCOLOR); + DrawWindow(40,82,250,45,BKGDCOLOR); + DrawWindow(40,147,250,32,BKGDCOLOR); + if(!VWB_DrawPic(100,0,C_FXTITLEPIC) || !VWB_DrawPic(100,65,C_DIGITITLEPIC) || + !VWB_DrawPic(100,130,C_MUSICTITLEPIC)) return false; + static const int ys[]={20,33,46,150,163}; + static const char *const labels[]={"None","AdLib effects","Adjust volumes","None","AdLib music"}; + for(unsigned i=0;i<5;++i) { + fontcolor=i==sound_choice?HIGHLIGHT:TEXTCOLOR;PrintX=100;PrintY=ys[i]; + if(!US_Print(labels[i])) return false; + if(i!=2) { + bool on=i==0?!eon:i==1?eon:i==3?!mon:mon; + if(!VWB_DrawPic(72,ys[i]+2,on?C_SELECTEDPIC:C_NOTSELECTEDPIC)) return false; + } + } + /* Digitized playback shares the existing effects enable/volume setting. + This is a status panel, not a second independently persisted device. */ + fontcolor=TEXTCOLOR;PrintX=100;PrintY=85; + if(!US_Print("With sound effects") || !VWB_DrawPic(72,87,eon && SD_DigitizedMode()?C_SELECTEDPIC:C_NOTSELECTEDPIC)) return false; + fontnumber=0;PrintX=80;PrintY=108; + if(!US_Print("Original digitized samples")) return false; + return VWB_DrawPic(48,ys[sound_choice]-2,MenuCursorPicture()); +} +bool BeginSoundSettings(void) +{ sound_choice=volume_choice=0;volume_page=false;MenuCursorMoved();IN_ClearKeysDown();return DrawSoundSettings(); } +int HandleSoundSettings(void) +{ + int direction=MenuNavigation();bool up=direction<0,down=direction>0; + bool left=IN_ConsumePress(sc_LeftArrow),right=IN_ConsumePress(sc_RightArrow); + bool enter=IN_ConsumePress(sc_Enter)|IN_ConsumePress(sc_Space); + if(IN_ConsumePress(sc_Escape)) { + (void)SD_PlaySound(ESCPRESSEDSND,0,0); + if(!volume_page) return -1; + volume_page=false;return DrawSoundSettings()?0:-3; + } + if(up || down) { + MenuCursorMoved(); + if(volume_page) volume_choice^=1U; + else sound_choice=(sound_choice+(up?4U:1U))%5; + (void)SD_PlaySound(MOVEGUN1SND,0,0); + } + if(left || right || enter) { + unsigned m,e;bool mon,eon;SD_GetSettings(&m,&e,&mon,&eon); + if(volume_page) { + unsigned *v=volume_choice?&e:&m; + if(left) *v=*v>=5?*v-5:0; + else *v=*v<=95?*v+5:100; + SD_SetVolumes(m,e); + } else { + if(sound_choice==0) eon=false; + else if(sound_choice==1) eon=true; + else if(sound_choice==2 && enter) { volume_page=true;volume_choice=0; } + else if(sound_choice==3) mon=false; + else if(sound_choice==4) mon=true; + SD_SetEnabled(mon,eon); + } + (void)SD_PlaySound(SHOOTSND,0,0); + } + if((up || down || left || right || enter) && !DrawSoundSettings()) return -3; + return 0; +} + +/* WL_MENU.C endStrings and Confirm. Keep DOS operator precedence: the + original expression is first & (7 + (second & 1)), not (first & 7)+bit. */ +const char *MenuQuitMessage(unsigned first,unsigned second) +{ + static const char *const sayings[]={ + "Dost thou wish to\nleave with such hasty\nabandon?", + "Chickening out...\nalready?", + "Press N for more carnage.\nPress Y to be a weenie.", + "So, you think you can\nquit this easily, huh?", + "Press N to save the world.\nPress Y to abandon it in\nits hour of need.", + "Press N if you are brave.\nPress Y to cower in shame.", + "Heroes, press N.\nWimps, press Y.", + "You are at an intersection.\nA sign says, 'Press Y to quit.'\n>", + "For guns and glory, press N.\nFor work and worry, press Y." + }; + return sayings[first & (7U+(second & 1U))]; +} +static int confirm_x,confirm_y,confirm_answer; +static uint64_t confirm_next; +static bool confirm_blink; +bool BeginConfirmation(const char *text,uint64_t ticks) { return BeginConfirmationAtHeight(text,ticks,200); } +bool BeginConfirmationAtHeight(const char *text,uint64_t ticks,unsigned height) +{ + if(!MessageAtHeight(text,height)) return false; + confirm_x=PrintX;confirm_y=PrintY;confirm_answer=0; + confirm_next=ticks+10;confirm_blink=false;IN_ClearKeysDown();return true; +} +int HandleConfirmation(uint64_t ticks) +{ + if(!confirm_answer) { + bool yes=IN_ConsumePress(sc_Y),no=IN_ConsumePress(sc_N)|IN_ConsumePress(sc_Escape); + if(yes || no) confirm_answer=yes?1:-1; + } + if(confirm_answer) { + if(Keyboard[sc_Y] || Keyboard[sc_N] || Keyboard[sc_Escape]) return 0; + int answer=confirm_answer;confirm_answer=0;IN_ClearKeysDown(); + (void)SD_PlaySound(answer>0?SHOOTSND:ESCPRESSEDSND,0,0);return answer; + } + if(ticks>=confirm_next) { + uint64_t count=(ticks-confirm_next)/10+1;confirm_next+=count*10; + /* DOS first erases, then draws, at ten-tic intervals. */ + bool draw=confirm_blink;if(count%2) confirm_blink=!confirm_blink; + if(count%2==0) draw=!draw; + VWB_Bar(confirm_x,confirm_y,8,13,TEXTCOLOR); + if(draw) { fontnumber=1;fontcolor=0;PrintX=confirm_x;PrintY=confirm_y;if(!US_Print("_")) return -3; } + } + return 0; +} + +/* WL_MENU.C DrawLSAction and WL_MAIN.C DiskFlopAnim. Native operation + phases expose both original disk pictures without blocking event polling. */ +bool DrawSaveActivity(bool saving,bool second) +{ + DrawWindow(96,80,130,42,TEXTCOLOR);DrawOutline(96,80,130,42,0,HIGHLIGHT); + if(!VWB_DrawPic(104,85,C_DISKLOADING1PIC+(second?1:0))) return false; + fontnumber=1;fontcolor=0;PrintX=142;PrintY=93; + return US_Print(saving?"Saving...":"Loading..."); +} diff --git a/src/engine/WL_MENU.h b/src/engine/WL_MENU.h new file mode 100644 index 00000000..1fc9e1de --- /dev/null +++ b/src/engine/WL_MENU.h @@ -0,0 +1,54 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_MENU_H +#define WL_MENU_H +#include +#include +#define BORDCOLOR 0x29 +#define BORD2COLOR 0x23 +#define DEACTIVE 0x2b +#define BKGDCOLOR 0x2d +#define STRIPE 0x2c +#define TEXTCOLOR 0x17 +#define HIGHLIGHT 0x13 +/* GOODTIMES layout selected by original VERSION.H: no Read This row. */ +enum { newgame, soundmenu, control, loadgame, savegame, changeview, viewscores, backtodemo, quit, MENU_COUNT }; +typedef struct { int x, y, amount, curpos, indent; } CP_iteminfo; +typedef struct { int active; const char *string; } CP_itemtype; +extern CP_iteminfo MainItems; +extern CP_itemtype MainMenu[MENU_COUNT]; +int MenuCursorPicture(void); +int MenuNavigation(void); /* Up/down edges and original 20-tick held repeat. */ +void MenuCursorMoved(void); +void ResetMenuCursor(uint64_t ticks); +bool TickMenuCursor(uint64_t ticks); +void ClearMScreen(void); +void DrawStripes(int y); +void DrawWindow(int x, int y, int w, int h, unsigned char color); +bool DrawMainMenu(void); +bool SetupControlPanel(uint64_t ticks); +/* -2: no action; -1: Escape, otherwise original menu item index. */ +int HandleMenu(uint64_t ticks); +bool DrawNewSelection(bool episode,unsigned choice); +int HandleNewSelection(uint64_t ticks,bool episode,unsigned *choice); +bool BeginControlsMenu(void); +bool ResumeControlsMenu(void); +bool DrawControlsMenu(void); +int HandleControlsMenu(void); +bool DrawSaveActivity(bool saving,bool second); +bool BeginSaveMenu(bool saving); +int HandleSaveMenu(uint64_t ticks); +unsigned SaveMenuSelected(void); +bool SaveMenuEditing(void); +bool DrawSoundSettings(void); +bool BeginSoundSettings(void); +int HandleSoundSettings(void); +bool Message(const char *text); +bool MessageAtHeight(const char *text,unsigned height); +/* Separate UI entropy: DOS quit selection must never advance gameplay RNG. */ +const char *MenuQuitMessage(unsigned first,unsigned second); +bool BeginConfirmation(const char *text,uint64_t ticks); +bool BeginConfirmationAtHeight(const char *text,uint64_t ticks,unsigned height); +/* -3 error, -1 cancelled, 0 pending, 1 accepted; waits for answer release. */ +int HandleConfirmation(uint64_t ticks); +bool DrawHighScores(void); +#endif diff --git a/src/engine/WL_OBJECT.c b/src/engine/WL_OBJECT.c new file mode 100644 index 00000000..ddc73b0c --- /dev/null +++ b/src/engine/WL_OBJECT.c @@ -0,0 +1,406 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_GAME.C ScanInfoPlane; WL_ACT1.C SpawnStatic/PlaceItemType; + WL_STATE.C SpawnNewObj/TryWalk, using bounded arrays instead of DOS tags. + Normal enemies use the original difficulty bands and hit-point tables; + Hans, Gretel and ghosts retain their specialised original spawn rules. */ +#include "WL_DEF.h" +#include "WL_PRESENT.h" +#include "ID_SD.h" +#include "ID_CA.h" +#include "ID_US_1.h" +#include +#include +objtype objlist[MAXACTORS],*actorat[64][64]; +statobj_t statobjlist[MAXSTATS]; +unsigned objcount,statcount; +static bool allocated[MAXACTORS],allocationfailed; +bool staticblock[64][64],spotvis[64][64],areabyplayer[37],madenoise; +int areaMap[64][64],thrustspeed; +gametype gamestate={.health=100,.ammo=8,.lives=3,.nextextra=40000,.weapon=wp_pistol,.bestweapon=wp_pistol,.chosenweapon=wp_pistol,.difficulty=2}; +extern statetype s_grdstand,s_grdpath1,s_grddie4,s_ofcstand,s_ofcpath1,s_ssstand,s_sspath1,s_mutstand,s_mutpath1,s_dogpath1; +extern statetype s_bossstand,s_gretelstand,s_blinkychase1,s_clydechase1,s_pinkychase1,s_inkychase1; +static void (*soundhook)(soundnames,const objtype *); +void SetGameSoundHook(void (*hook)(soundnames,const objtype *)) { soundhook=hook; } +static int32_t soundx,soundy; +static bool soundpositioned; +/* WL_GAME.C SetSoundLoc. Original tables and camera focal offset. */ +static const unsigned char lefttable[15][30] = { +{ 8, 8, 8, 8, 8, 8, 8, 8, 5, 3, 1, 0, 0, 0, 0, 0, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 6, 4, 2, 0, 0, 0, 0, 0, 4, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 6, 4, 2, 1, 0, 0, 0, 1, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 7, 5, 3, 2, 1, 0, 1, 2, 4, 5, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 6, 5, 3, 3, 2, 2, 3, 4, 5, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 6, 5, 4, 4, 4, 4, 5, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 6, 6, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8} +}; +static const unsigned char righttable[15][30] = { +{ 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 6, 0, 0, 0, 0, 0, 1, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 6, 4, 0, 0, 0, 0, 0, 2, 4, 6, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 6, 6, 4, 1, 0, 0, 0, 1, 2, 4, 6, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 6, 5, 4, 2, 1, 0, 1, 2, 3, 5, 7, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 6, 5, 4, 3, 2, 2, 3, 3, 5, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 6, 6, 5, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 6, 6, 5, 5, 5, 6, 6, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, +{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8} +}; +void GameSoundPosition(int32_t gx,int32_t gy,unsigned *left,unsigned *right) +{ + if(player.angle<0 || player.angle>=360) { *left=*right=0;return; } + uint32_t vs=sintable[player.angle],vc=sintable[player.angle+90]; + int32_t vx=player.x-FixedByFrac(FOCALLENGTH,vc),vy=player.y+FixedByFrac(FOCALLENGTH,vs); + gx-=vx;gy-=vy; + int x=WL_FloorShift((int64_t)FixedByFrac(gx,vc)-FixedByFrac(gy,vs),16); + int y=WL_FloorShift((int64_t)FixedByFrac(gy,vc)+FixedByFrac(gx,vs),16); + if(x<0) x=-x; + if(x>=15) x=14; + if(y>=15) y=14; + if(y< -15) y=-15; + *left=lefttable[x][y+15];*right=righttable[x][y+15]; +} +void UpdateSoundLoc(void) +{ + if(soundpositioned) { unsigned left,right;GameSoundPosition(soundx,soundy,&left,&right);SD_SetPosition(left,right); } +} +void GameSound(soundnames sound,const objtype *actor) +{ + unsigned left=0,right=0; + if(actor) GameSoundPosition(actor->x,actor->y,&left,&right); + if(SD_PlaySound(sound,left,right) && SD_IsDigitizedSound(sound)) { soundpositioned=actor!=NULL; + if(actor) { soundx=actor->x;soundy=actor->y; } } + if (soundhook) soundhook(sound,actor); +} +void InitObjects(void) +{ + objcount=statcount=0;player.next=NULL;player.state=NULL;madenoise=false; + memset(allocated,0,sizeof(allocated));allocationfailed=false; + memset(objlist,0,sizeof(objlist));memset(actorat,0,sizeof(actorat)); + memset(staticblock,0,sizeof(staticblock));memset(spotvis,0,sizeof(spotvis)); + memset(areabyplayer,0,sizeof(areabyplayer)); +} +/* WL_PLAY.C GetNewActor/RemoveObj, with an explicit bounded failure path. + objcount is the occupied-array high-water mark, not the linked-list count. */ +bool ActorAllocationFailed(void) { return allocationfailed; } +objtype *GetNewActor(void) +{ + unsigned slot=0;while (slot=objcount) objcount=slot+1; + objtype *tail=&player;while (tail->next) tail=tail->next; + tail->next=ob;return ob; +} +void RemoveActor(objtype *ob) +{ + if (!ob || ob==&player) return; + objtype *prev=&player;while (prev->next && prev->next!=ob) prev=prev->next; + if (prev->next!=ob) return; + prev->next=ob->next; + for (int x=0;x<64;++x) for (int y=0;y<64;++y) + if (actorat[x][y]==ob) actorat[x][y]=NULL; + allocated[ob-objlist]=false;ob->state=NULL;ob->flags=0; +} +objtype *SpawnActor(int x,int y,statetype *state) +{ + if (x<1 || y<1 || x>62 || y>62) { + allocationfailed=true;(void)CA_Fail("Invalid actor position");return NULL; + } + objtype *ob=GetNewActor();if (!ob) return NULL; + ob->state=state;ob->ticcount=state->tictime ? US_RndT()%state->tictime : 0; + ob->x=x*TILEGLOBAL+32768;ob->y=y*TILEGLOBAL+32768; + ob->tilex=x;ob->tiley=y;ob->areanumber=areaMap[x][y];ob->dir=nodir; + actorat[x][y]=ob;return ob; +} +void NewState(objtype *ob,statetype *state) { ob->state=state;ob->ticcount=state->tictime; } +static const int dirx[9]={1,1,0,-1,-1,-1,0,1,0}; +static const int diry[9]={0,-1,-1,-1,0,1,1,1,0}; +static bool CheckTile(int x,int y,bool diagonal,int *door) +{ + if (x<=0 || y<=0 || x>=63 || y>=63) return false; + if (actorat[x][y]) return !(actorat[x][y]->flags&FL_SHOOTABLE); + if (staticblock[x][y]) return false; + unsigned tile=tilemap[x][y]; + if (!tile || tile==64) return true; + if (!(tile&128) || (tile&64)) return false; + if (!DoorSolid(tile&63)) return true; + if (diagonal) return false; + *door=(int)(tile&63);return true; +} +bool TryWalk(objtype *ob) +{ + if (ob->dir<0 || ob->dir>=nodir) return false; + int dx=dirx[ob->dir],dy=diry[ob->dir],x=ob->tilex+dx,y=ob->tiley+dy,door=-1; + bool diag=dx && dy; + if (!CheckTile(x,y,diag || ob->obclass==dogobj || ob->obclass==fakeobj,&door)) return false; + if (diag && (!CheckTile(ob->tilex+dx,ob->tiley,true,&door) || + !CheckTile(ob->tilex,ob->tiley+dy,true,&door))) return false; + ob->tilex=x;ob->tiley=y; + if (door>=0) { OpenDoor((unsigned)door);ob->distance=-door-1;return true; } + ob->areanumber=areaMap[x][y];ob->distance=TILEGLOBAL;return true; +} +/* Original area graph semantics: a door connects its two areas as soon as + its first opening tic advances, and disconnects only after it closes. Rebuilding + the small graph avoids stale counters during level restarts. */ +void ConnectAreas(void) +{ + memset(areabyplayer,0,sizeof(areabyplayer)); + int area=areaMap[player.tilex][player.tiley]; + areabyplayer[area]=true; + for (unsigned pass=0;pass<37;++pass) { + bool changed=false; + for (unsigned i=0;iaction==dr_closed || (d->action==dr_opening && !d->position)) continue; + int a=areaMap[d->x-(d->vertical?1U:0U)][d->y-(d->vertical?0U:1U)]; + int b=areaMap[d->x+(d->vertical?1U:0U)][d->y+(d->vertical?0U:1U)]; + if (areabyplayer[a]!=areabyplayer[b]) { areabyplayer[a]=areabyplayer[b]=true;changed=true; } + } + if (!changed) break; + } +} + +static const struct { int picnum;stat_t type; } statinfo[] = { +{SPR_STAT_0,dressing}, +{SPR_STAT_1,block}, +{SPR_STAT_2,block}, +{SPR_STAT_3,block}, +{SPR_STAT_4,dressing}, +{SPR_STAT_5,block}, +{SPR_STAT_6,bo_alpo}, +{SPR_STAT_7,block}, +{SPR_STAT_8,block}, +{SPR_STAT_9,dressing}, +{SPR_STAT_10,block}, +{SPR_STAT_11,block}, +{SPR_STAT_12,block}, +{SPR_STAT_13,block}, +{SPR_STAT_14,dressing}, +{SPR_STAT_15,dressing}, +{SPR_STAT_16,block}, +{SPR_STAT_17,block}, +{SPR_STAT_18,block}, +{SPR_STAT_19,dressing}, +{SPR_STAT_20,bo_key1}, +{SPR_STAT_21,bo_key2}, +{SPR_STAT_22,block}, +{SPR_STAT_23,dressing}, +{SPR_STAT_24,bo_food}, +{SPR_STAT_25,bo_firstaid}, +{SPR_STAT_26,bo_clip}, +{SPR_STAT_27,bo_machinegun}, +{SPR_STAT_28,bo_chaingun}, +{SPR_STAT_29,bo_cross}, +{SPR_STAT_30,bo_chalice}, +{SPR_STAT_31,bo_bible}, +{SPR_STAT_32,bo_crown}, +{SPR_STAT_33,bo_fullheal}, +{SPR_STAT_34,bo_gibs}, +{SPR_STAT_35,block}, +{SPR_STAT_36,block}, +{SPR_STAT_37,block}, +{SPR_STAT_38,bo_gibs}, +{SPR_STAT_39,block}, +{SPR_STAT_40,block}, +{SPR_STAT_41,dressing}, +{SPR_STAT_42,dressing}, +{SPR_STAT_43,dressing}, +{SPR_STAT_44,dressing}, +{SPR_STAT_45,block}, +{SPR_STAT_46,block}, +{SPR_STAT_47,dressing}, +{SPR_STAT_26,bo_clip2}, +{-1,dressing} +}; + +static bool SpawnStatic(int x,int y,unsigned type) +{ + if (type>=48 || statcount>=MAXSTATS) return CA_Fail("Too many/invalid static objects"); + if (statinfo[type].type==block && actorat[x][y] && (actorat[x][y]->flags&FL_SHOOTABLE)) + return CA_Fail("Blocking object on actor destination"); + statobj_t *ob=&statobjlist[statcount++]; + ob->tilex=x;ob->tiley=y;ob->shapenum=statinfo[type].picnum;ob->itemnumber=statinfo[type].type; + ob->bonus=ob->itemnumber>=bo_gibs; + if (ob->itemnumber==block) staticblock[x][y]=true; + if ((ob->itemnumber>=bo_cross && ob->itemnumber<=bo_crown) || ob->itemnumber==bo_fullheal) ++gamestate.treasuretotal; + return true; +} +void PlaceItemType(stat_t item,int x,int y) +{ + if (x<=0 || y<=0 || x>=63 || y>=63) return; + unsigned type=0; + while (statinfo[type].picnum!=-1 && statinfo[type].type!=item) ++type; + if (statinfo[type].picnum==-1) return; + unsigned slot=0; + while (slot=MAXSTATS) return; + if (slot==statcount) ++statcount; + statobjlist[slot]=(statobj_t){x,y,statinfo[type].picnum,item,true}; +} +static bool SpawnNewObj(int x,int y,statetype *state,int kind,int direction,bool patrol,bool dead) +{ + if (objcount>=MAXACTORS || x<=0 || y<=0 || x>=63 || y>=63 || (tilemap[x][y] && tilemap[x][y]!=64)) return CA_Fail("Invalid/too many actors"); + objtype *ob=SpawnActor(x,y,state);if (!ob) return false; + ob->dir=direction*2;ob->areanumber=areaMap[x][y];ob->obclass=dead ? inertobj : kind; + if (!dead) { + ob->flags=FL_SHOOTABLE; + if (!patrol && CA_Map()->planes[0][y*64+x]==106) ob->flags|=FL_AMBUSH; + ob->speed=kind==dogobj ? SPDDOG : SPDPATROL; + ob->hitpoints=kind==guardobj ? 25 : kind==officerobj ? 50 : kind==ssobj ? 100 : kind==dogobj ? 1 : gamestate.difficulty==0 ? 45 : gamestate.difficulty==3 ? 65 : 55; + ++gamestate.killtotal; + } + if (patrol) { + /* SpawnPatrol reserves the initial forward tile unconditionally, + even a closed door (owned E4M6 on hard). Keep that original move. */ + actorat[x][y]=NULL; /* Original SpawnPatrol releases its birth tile. */ + ob->active=true;ob->distance=TILEGLOBAL; + ob->tilex+=dirx[ob->dir];ob->tiley+=diry[ob->dir]; + if (ob->tilex<=0 || ob->tiley<=0 || ob->tilex>=63 || ob->tiley>=63) + return CA_Fail("Invalid actor patrol destination"); + } + /* Original scan order can overwrite a reserved destination (E5M4). + Both actors remain in the object list; the last mark owns actorat. */ + actorat[ob->tilex][ob->tiley]=ob;return true; +} +/* WL_ACT2.C original boss spawning and SpawnGhosts. Ghosts intentionally + have no FL_SHOOTABLE or health assignment, despite the unused HP table. */ +static bool SpawnSpecial(int x,int y,unsigned tile) +{ + static const int health[4]={850,950,1050,1200}; + static statetype *const ghosts[]={&s_blinkychase1,&s_clydechase1,&s_pinkychase1,&s_inkychase1}; + bool ghost=tile>=224; + statetype *state=NULL;int kind=ghostobj,dir=east,hp=0; + if (ghost) state=ghosts[tile-224]; + else { + hp=health[gamestate.difficulty]; + switch (tile) { + case 214:state=&s_bossstand;kind=bossobj;dir=south;break; + case 197:state=&s_gretelstand;kind=gretelobj;dir=north;break; + case 196: { + static const int schabbhp[]={850,950,1550,2400}; + state=&s_schabbstand;kind=schabbobj;dir=south;hp=schabbhp[gamestate.difficulty];break; + } + case 215:state=&s_giftstand;kind=giftobj;dir=north;break; + case 179:state=&s_fatstand;kind=fatobj;dir=south;break; + case 160:state=&s_fakestand;kind=fakeobj;dir=north;hp=200+100*gamestate.difficulty;break; + case 178: { + static const int mecha[]={800,950,1050,1200}; + state=&s_mechastand;kind=mechahitlerobj;dir=south;hp=mecha[gamestate.difficulty];break; + } + } + } + if (!state || !SpawnNewObj(x,y,state,kind,0,false,false)) return false; + objtype *ob=&objlist[objcount-1]; + ob->flags=FL_AMBUSH|(ghost ? 0U : FL_SHOOTABLE);ob->dir=dir; + ob->speed=ghost ? SPDDOG : SPDPATROL;ob->hitpoints=hp; + /* Original logical DigiMode selects timing, never mute or device status. */ + s_schabbdie2.tictime=s_giftdie2.tictime=s_fatdie2.tictime=s_hitlerdie2.tictime=SD_DigitizedMode()?140:5; + return true; +} +bool ScanInfoPlane(void) +{ + const maptype *map=CA_Map(); + for (int y=0;y<64;++y) for (int x=0;x<64;++x) { + unsigned raw=map->planes[0][y*64+x]; + if (raw==106) { + /* Original SpawnStand neighbour priority: E, N, S, then W. */ + const int ox[4]={1,0,0,-1},oy[4]={0,-1,1,0};raw=107; + for (unsigned i=0;i<4;++i) { + int nx=x+ox[i],ny=y+oy[i]; + if (nx>=0 && ny>=0 && nx<64 && ny<64 && map->planes[0][ny*64+nx]>=107) raw=map->planes[0][ny*64+nx]; + } + } + areaMap[x][y]=raw>=107 ? (int)raw-107 : 0; + } + for (unsigned i=0;ix][d->y]=areaMap[d->x-(d->vertical?1U:0U)][d->y-(d->vertical?0U:1U)]; + } + for (int y=0;y<64;++y) for (int x=0;x<64;++x) { + unsigned tile=map->planes[1][y*64+x]; + if (tile>=23 && tile<=70 && !SpawnStatic(x,y,tile-23)) return false; + if (tile==124) { if (!SpawnNewObj(x,y,&s_grddie4,inertobj,0,false,true)) return false;continue; } + if (tile==98) { + if (!tilemap[x][y] || tilemap[x][y]>=64) return CA_Fail("Invalid pushwall marker"); + pushable[x][y]=true;++gamestate.secrettotal;continue; + } + if (tile==214 || tile==197 || tile==196 || tile==215 || tile==179 || + tile==160 || tile==178 || (tile>=224 && tile<=227)) { + if (!SpawnSpecial(x,y,tile)) return false; + continue; + } + /* EXITTILE is a movement trigger, not an actor to allocate at startup. */ + if (tile==99) { + if (x<1 || y<1 || x>62 || y>61 || (tilemap[x][y] && tilemap[x][y]!=64)) + return CA_Fail("Invalid victory tile"); + continue; + } + /* WL_GAME.C ScanInfoPlane: two 36-code normal-enemy bands; + mutants have their own two 18-code bands. Exclude boss codes. */ + if (tile>=180 && tile<=213) { if (gamestate.difficulty<3) continue;tile-=36; } + if (tile>=144 && tile<=177) { if (gamestate.difficulty<2) continue;tile-=36; } + if (tile>=252 && tile<=259) { if (gamestate.difficulty<3) continue;tile-=18; } + if (tile>=234 && tile<=241) { if (gamestate.difficulty<2) continue;tile-=18; } + statetype *state=NULL;int kind=guardobj,dir=0;bool patrol=false; + if (tile>=108 && tile<=115) { dir=(int)(tile-108)%4;patrol=tile>=112;state=patrol?&s_grdpath1:&s_grdstand; } + else if (tile>=116 && tile<=123) { kind=officerobj;dir=(int)(tile-116)%4;patrol=tile>=120;state=patrol?&s_ofcpath1:&s_ofcstand; } + else if (tile>=126 && tile<=133) { kind=ssobj;dir=(int)(tile-126)%4;patrol=tile>=130;state=patrol?&s_sspath1:&s_ssstand; } + else if (tile>=138 && tile<=141) { kind=dogobj;dir=(int)tile-138;patrol=true;state=&s_dogpath1; } + else if (tile>=216 && tile<=223) { kind=mutantobj;dir=(int)(tile-216)%4;patrol=tile>=220;state=patrol?&s_mutpath1:&s_mutstand; } + /* Original SpawnStand has no dog case; these unused codes are unsafe. */ + else if (tile>=134 && tile<=137) return CA_Fail("Unsupported stationary dog spawn %u",tile); + if (state && !SpawnNewObj(x,y,state,kind,dir,patrol,false)) return false; + } + ConnectAreas();return true; +} +/* WL_ACT2.C A_DeathScream, registered (non-UPLOAD), non-SPEAR version. + The easter-egg draw uses ID_CA's absolute mapon, not episode-local mapon. */ +void A_DeathScream(objtype *ob) +{ + if (gamestate.episode*10+gamestate.mapon==9 && !US_RndT()) { + switch (ob->obclass) { + case mutantobj:case guardobj:case officerobj:case ssobj:case dogobj: + GameSound(DEATHSCREAM6SND,ob);return; + } + } + switch (ob->obclass) { + case guardobj: { + static const soundnames sounds[]={DEATHSCREAM1SND,DEATHSCREAM2SND, + DEATHSCREAM3SND,DEATHSCREAM4SND,DEATHSCREAM5SND,DEATHSCREAM7SND, + DEATHSCREAM8SND,DEATHSCREAM9SND}; + GameSound(sounds[US_RndT()%8],ob);break; + } + case mutantobj:GameSound(AHHHGSND,ob);break; + case officerobj:GameSound(NEINSOVASSND,ob);break; + case ssobj:GameSound(LEBENSND,ob);break; + case dogobj:GameSound(DOGDEATHSND,ob);break; + case bossobj:GameSound(MUTTISND,NULL);break; + case gretelobj:GameSound(MEINSND,NULL);break; + case schabbobj:GameSound(MEINGOTTSND,NULL);break; + case giftobj:GameSound(DONNERSND,NULL);break; + case fatobj:GameSound(ROSESND,NULL);break; + case fakeobj:GameSound(HITLERHASND,NULL);break; + case mechahitlerobj:GameSound(SCHEISTSND,NULL);break; + case realhitlerobj:GameSound(EVASND,NULL);break; + } +} + +bool Save_ActorAllocated(unsigned slot) { return slot0) damagecount=damage>1000-damagecount ? 1000 : damagecount+damage; +} +void FinishPaletteShifts(void) +{ + if (palshifted) { (void)VL_SetPalette(gamepal,768);palshifted=false; } +} +bool UpdatePaletteShifts(void) +{ + int white=bonuscount ? bonuscount/6+1 : 0,red=damagecount ? damagecount/10+1 : 0; + if (white>3) white=3; + if (red>6) red=6; + if (bonuscount) { bonuscount-=SimulationTics();if(bonuscount<0) bonuscount=0; } + if (damagecount) { damagecount-=SimulationTics();if(damagecount<0) damagecount=0; } + if (red || white) { + palshifted=true; + return VL_SetPalette(red ? redshifts[red-1] : whiteshifts[white-1],768); + } + FinishPaletteShifts();return true; +} diff --git a/src/engine/WL_PLAY.c b/src/engine/WL_PLAY.c new file mode 100644 index 00000000..de8239d4 --- /dev/null +++ b/src/engine/WL_PLAY.c @@ -0,0 +1,241 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_PLAY.C controls and clock: normal play uses one 70-Hz tic per update; + original demo commands use four-tic frames. Presentation is independent. */ +#include "WL_DEF.h" +#include "WL_PRESENT.h" +#include "WL_DEMO.h" +#include "WL_SAVE.h" +#include "WL_CONTROLS.h" +#include "ID_IN.h" +#include "ID_CA.h" +#include "ID_SD.h" +#include "ID_VH.h" +#include "ID_US_1.h" +#include +static uint64_t lasttimecount; +static bool running,finished,intermission; +static unsigned victorypage; +static bool preload_pending; +bool GamePreloadPending(void) { return preload_pending; } +void GamePreloadConsumed(void) { preload_pending=false; } +bool GameVictoryPresentation(void) { return victorypage!=0; } +bool GameIntermission(void) { return intermission; } +static unsigned deathphase,deathwait; +static int deathangle; +static uint32_t fizzlernd; +unsigned GameDeathPresentation(uint32_t *seed) +{ + if(seed) *seed=fizzlernd; + return running && gamestate.died?deathphase:0; +} +bool GameFinished(void) { return finished; } +void DrawPlayBorder(void) +{ + VWB_Bar(0,0,320,160,127); + VWB_Bar(VIEWX,VIEWY,VIEWWIDTH,VIEWHEIGHT,0); + VWB_Hlin(VIEWX-1,VIEWX+VIEWWIDTH,VIEWY-1,0); + VWB_Hlin(VIEWX-1,VIEWX+VIEWWIDTH,VIEWY+VIEWHEIGHT,125); + VWB_Vlin(VIEWY-1,VIEWY+VIEWHEIGHT,VIEWX-1,0); + VWB_Vlin(VIEWY-1,VIEWY+VIEWHEIGHT,VIEWX+VIEWWIDTH,125); + framebuffer[(VIEWY+VIEWHEIGHT)*320+VIEWX-1]=124; +} +static bool DrawPlayScreen(void) +{ + DrawPlayBorder();return VWB_DrawPic(0,160,STATUSBARPIC) && DrawStatus(); +} +bool GameProbe(void) +{ + US_InitRndT(0); + bool valid=NewGame(2,0) && SetupGameLevel() && DrawPlayScreen() && ThreeDRefresh(); + ShutdownGameLevel(); return valid; +} +bool GameStart(uint64_t ticks) { return GameStartSelected(ticks,0,2); } +bool GameStartSelected(uint64_t ticks,unsigned episode,unsigned difficulty) +{ + if(episode>5) { GameStop();return CA_Fail("Invalid episode/difficulty"); } + return GameStartMap(ticks,episode*10,difficulty,(unsigned)(ticks&255U)); +} +bool GameStartMap(uint64_t ticks,unsigned map,unsigned difficulty,unsigned seed) +{ + GameStop(); + if(map>=60) return CA_Fail("Invalid original map number"); + if(!NewGame(difficulty,map/10)) return false; + gamestate.mapon=(int)(map%10);US_InitRndT(seed); + if (!SetupGameLevel() || !DrawPlayScreen() || !ThreeDRefresh()) { GameStop(); return false; } + SD_StartMusic(SD_LevelMusic(map/10,map%10)); + deathphase=deathwait=0;finished=intermission=false; + preload_pending=true;lasttimecount=ticks;running=true; IN_ClearKeysDown();WL_PresentCapture(ticks);return true; +} +/* WL_DEBUG.C Tab-W returns ex_warped to GameLoop: preserve inventory and + episode, restore entry score, then perform the ordinary level setup. */ +bool GameWarp(uint64_t ticks,unsigned floor) +{ + if(!GameCanSave() || floor<1 || floor>10) return CA_Fail("Invalid debug warp"); + ShutdownGameLevel();gamestate.mapon=(int)floor-1;gamestate.score=gamestate.oldscore; + US_InitRndT((unsigned)(ticks&255U)); + if(!SetupGameLevel() || !DrawPlayScreen() || !ThreeDRefresh()) { GameStop();return false; } + SD_StartMusic(SD_LevelMusic((unsigned)gamestate.episode,(unsigned)gamestate.mapon)); + preload_pending=true;deathphase=deathwait=0;lasttimecount=ticks;IN_ClearKeysDown();WL_PresentReset();WL_PresentCapture(ticks);return true; +} +void GameStop(void) { preload_pending=false;ResetPreloadGraphics(); WL_PresentReset(); Demo_Stop();CT_SetGameplay(false);SD_StopSound();SD_StartMusic(-1); victorypage=0;ResetEndText(); FinishPaletteShifts();running=intermission=false; ShutdownGameLevel(); } +/* WL_GAME.C Died and ID_VH.C FizzleFade, resumed one original tic at a + time instead of blocking the SDL event loop. The 17-bit polynomial and + 64000/70 candidate pixels per tic are the original values. */ +static bool Died(uint64_t ticks) +{ + if (!deathphase) { + gamestate.weapon=-1; + SD_StartMusic(-1);GameSound(PLAYERDEATHSND,NULL); + if (killerobj) { + float angle=(float)atan2((double)player.y-killerobj->y,(double)killerobj->x-player.x); + if (angle<0) angle=(float)(6.28318530717958647692+angle); + deathangle=(int)(angle/6.28318530717958647692*ANGLES)%ANGLES; + } else deathangle=player.angle; + deathphase=1; + } + if (deathphase==1) { + /* DOS clockwise2 ? 2 : delta< -2 ? -2 : delta; + player.angle=(player.angle+change+360)%360; + if (!ThreeDRefresh() || !DrawStatus()) return false; + if (player.angle==deathangle) { FinishPaletteShifts();deathphase=2;fizzlernd=1;IN_ClearKeysDown(); } + } else if (deathphase==2) { + for (unsigned p=0;p<64000/70;++p) { + unsigned x=fizzlernd>>8,y=(fizzlernd-1)&255U; + fizzlernd=(fizzlernd>>1)^((fizzlernd&1U)?UINT32_C(0x12000):0U); + /* Original x>width/y>height allowed border writes. Clip to the + actual viewport here, preserving its surrounding bevel. */ + if (x8) elapsed=8; + } else lasttimecount=ticks; + if (elapsed>MAXTICS) elapsed=MAXTICS; /* Discard long-pause excess, as CalcTics. */ + if (intermission) { + bool leave=false; + if(!StepLevelIntermission(ticks,IN_AnyPressed(),&leave)) return false; + if(!leave) return true; + unsigned next=NextMap((unsigned)gamestate.episode,(unsigned)gamestate.mapon,playstate); + if (next>=60 || next/10!=(unsigned)gamestate.episode) return CA_Fail("Invalid campaign progression"); + gamestate.oldscore=gamestate.score;gamestate.mapon=(int)(next%10); + ShutdownGameLevel(); + if (!SetupGameLevel() || !DrawPlayScreen() || !ThreeDRefresh()) return false; + SD_StartMusic(SD_LevelMusic((unsigned)gamestate.episode,(unsigned)gamestate.mapon)); + preload_pending=true;intermission=false;IN_ClearKeysDown();WL_PresentCapture(ticks);return true; + } + if (victorypage) { + if (victorypage==1) { + if (IN_AnyPressed()) { + IN_ClearKeysDown();if (!StartEndText()) return false;victorypage=2; + } + } else { + bool done=false;if (!StepEndText(&done)) return false; + if (done) { finished=true;ResetEndText(); } + } + return true; + } + for (uint64_t tic=0;tic1) strafe=1;if(strafe< -1) strafe=-1; } + ModernMovement(turn*move+mouse_turn,forward,strafe,move); + } + ConnectAreas(); + if (!gamestate.victoryflag) T_Attack(playback?(demo.buttons&1U)!=0:CT_Down(CT_FIRE)); + for (objtype *ob=player.next;ob;ob=ob->next) { + DoActor(ob);if (DeathCameraActive()) break; + } + if (ActorAllocationFailed()) return false; + UpdateSoundLoc(); + madenoise=false; + IN_ClearPressed();CT_EndTic(); + /* A_StartDeathCam's original blocking hold begins before the outer + palette update. Keep that ordering while its wait is resumed. */ + if ((!DeathCameraActive() && !UpdatePaletteShifts()) || !ThreeDRefresh() || !DrawStatus()) return false; + WL_PresentCapture(ticks-elapsed+tic+dt); + } + return true; +} + +bool GameRunning(void) { return running && !finished; } +bool GameCanSave(void) +{ + return GameRunning() && !GameLoading() && !Demo_Active() && CA_Map() && !intermission && !victorypage && !gamestate.died && + !gamestate.victoryflag && !DeathCameraActive() && playstate==ex_playing && !ActorAllocationFailed(); +} +void GamePauseClock(uint64_t ticks) { lasttimecount=ticks;WL_PresentReset();WL_PresentCapture(ticks); } +void GameRestoreClock(uint64_t ticks) +{ + WL_PresentReset();running=true;finished=intermission=false;victorypage=0;deathphase=deathwait=0; + preload_pending=true;lasttimecount=ticks;ResetVictory();ResetEndText();ClearPaletteShifts();WL_PresentCapture(ticks); +} +bool GameDrawPaused(void) { InvalidateStatus();return DrawPlayScreen() && ThreeDRefreshPaused(); } diff --git a/src/engine/WL_PRESENT.c b/src/engine/WL_PRESENT.c new file mode 100644 index 00000000..600bc458 --- /dev/null +++ b/src/engine/WL_PRESENT.c @@ -0,0 +1,103 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "WL_PRESENT.h" +#include "WL_DEMO.h" +#include "WL_SAVE.h" +#include "WL_RENDER.h" +#include "ID_CA.h" +#include "WL_PROFILE.h" +#include +#include +#include +static wl_present_snapshot previous,current; +static wl_frame_clock clock_state; +static uint64_t identities[MAXACTORS],next_identity,last_tick; +static bool ready; +void WL_PresentReset(void) { ready=false;WL_FrameClockReset(&clock_state); } +void WL_PresentAllocated(unsigned slot) +{ if(slot=360) value-=360; + return value; +} +void WL_PresentCapture(uint64_t tick) +{ + if(!GameRunning() || !CA_Map()) { WL_PresentReset();return; } + WL_PROFILE_BEGIN(capture_start); + previous=current;memset(¤t,0,sizeof(current)); + current.camera=(wl_pose){player.x,player.y,player.angle}; + memcpy(current.tiles,tilemap,sizeof(tilemap));memcpy(current.doors,doorobjlist,sizeof(doorobjlist));current.door_count=doornum; + memcpy(current.statics,statobjlist,sizeof(statobjlist));current.static_count=statcount; + current.push_x=pwallx;current.push_y=pwally;current.push_dir=pwalldir;current.push_state=pwallstate;current.push_offset=(int32_t)(pwallpos*1024); + current.level=(unsigned)(gamestate.episode*10+gamestate.mapon);current.view_size=ViewSize();current.simulation_clock=gamestate.TimeCount; + current.ceiling=WL_CeilingColor();current.death_phase=GameDeathPresentation(¤t.death_cursor); + /* Died uses DOS weapon=-1; snapshots retain a valid unsigned index + even though the died flag suppresses the held weapon entirely. */ + current.weapon=gamestate.weapon<0?0U:(unsigned)gamestate.weapon;current.weapon_frame=(unsigned)gamestate.weaponframe; + current.died=gamestate.died;current.victory=gamestate.victoryflag;current.demo=Demo_Active(); + for(const objtype *o=player.next;o;o=o->next) { + unsigned slot=(unsigned)(o-objlist);if(slot>=MAXACTORS || !o->state) continue; + wl_present_actor *a=¤t.actors[slot]; + a->identity=identities[slot];a->x=o->x;a->y=o->y;a->dir=o->dir;a->angle=o->angle;a->kind=o->obclass; + a->shape=o->state->shapenum<0?o->temp1:o->state->shapenum;a->rotate=o->state->rotate; + a->facing=o->obclass==rocketobj?o->angle:(o->dir<8?o->dir*45:0); + current.order[current.count++]=slot; + } + bool snap=!ready || current.level!=previous.level || current.view_size!=previous.view_size || + tick<=last_tick || current.victory || + current.demo!=previous.demo || current.simulation_clockTILEGLOBAL*2 || + llabs((long long)current.camera.y-previous.camera.y)>TILEGLOBAL*2; + if(snap) { previous=current;WL_FrameClockReset(&clock_state); } + WL_FrameClockObserve(&clock_state,WL_TickNS(tick));last_tick=tick;ready=true;WL_PROFILE_END(capture,capture_start); +} +const wl_present_snapshot *WL_PresentCurrent(void) { return ready?¤t:NULL; } +bool WL_PresentSample(uint64_t now_ns,wl_present_snapshot *out) +{ + if(!ready || !out) return false; + WL_PROFILE_BEGIN(sample_start); + *out=current;double alpha=WL_FrameClockAlpha(&clock_state,now_ns); + out->camera.x=Lerp(previous.camera.x,current.camera.x,alpha);out->camera.y=Lerp(previous.camera.y,current.camera.y,alpha); + out->camera.angle=WL_PresentAngle(previous.camera.angle,current.camera.angle,alpha); + for(unsigned i=0;ix-a->x)>TILEGLOBAL*2 || llabs((long long)b->y-a->y)>TILEGLOBAL*2) continue; + out->actors[i].x=Lerp(a->x,b->x,alpha);out->actors[i].y=Lerp(a->y,b->y,alpha); + out->actors[i].angle=(int)WL_PresentAngle(a->angle,b->angle,alpha); + if(a->kind==b->kind && a->rotate==b->rotate) + out->actors[i].facing=WL_PresentAngle(a->facing,b->facing,alpha); + } + for(unsigned i=0;idoors[i].position=(uint16_t)Lerp(previous.doors[i].position,current.doors[i].position,alpha); + int dx=current.push_x-previous.push_x,dy=current.push_y-previous.push_y; + static const int push_dx[8]={1,0,0,0,-1,0,0,0},push_dy[8]={0,0,-1,0,0,0,1,0}; + bool same_tile=dx==0 && dy==0; + bool adjacent=current.push_dir>=0 && current.push_dir<8 && !(current.push_dir&1) && + dx==push_dx[current.push_dir] && dy==push_dy[current.push_dir]; + if(previous.push_state && previous.push_dir==current.push_dir && + (same_tile || adjacent)) { + bool crossing=previous.push_x!=current.push_x || previous.push_y!=current.push_y || !current.push_state; + int32_t end=crossing?65536+(!current.push_state?0:current.push_offset):current.push_offset; + int32_t offset=Lerp(previous.push_offset,end,alpha); + if(crossing && offset<65536) { + out->push_x=previous.push_x;out->push_y=previous.push_y; + out->tiles[previous.push_x][previous.push_y]=previous.tiles[previous.push_x][previous.push_y]; + if(adjacent) { + out->tiles[current.push_x][current.push_y]=previous.tiles[current.push_x][current.push_y]; + int nx=current.push_x+push_dx[current.push_dir],ny=current.push_y+push_dy[current.push_dir]; + if(current.push_state && nx>=0 && nx<64 && ny>=0 && ny<64) + out->tiles[nx][ny]=previous.tiles[nx][ny]; + } + } + out->push_offset=offset>=65536?offset-65536:offset; + } + WL_PROFILE_END(sample,sample_start);return true; +} diff --git a/src/engine/WL_PRESENT.h b/src/engine/WL_PRESENT.h new file mode 100644 index 00000000..2933b916 --- /dev/null +++ b/src/engine/WL_PRESENT.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_PRESENT_H +#define WL_PRESENT_H +#include "WL_DEF.h" +#include "WL_FRAME_CLOCK.h" +typedef struct { + int32_t x,y;double angle; +} wl_pose; +typedef struct { + int32_t x,y;int shape,rotate,dir,angle,kind;uint64_t identity;double facing; +} wl_present_actor; +typedef struct { + wl_pose camera; + wl_present_actor actors[MAXACTORS];unsigned order[MAXACTORS],count; + statobj_t statics[MAXSTATS];unsigned static_count; + w3r_byte tiles[64][64];doorobj_t doors[64];unsigned door_count; + int push_x,push_y,push_dir;unsigned push_state;int32_t push_offset; + unsigned level,view_size,weapon,weapon_frame;uint32_t simulation_clock; + unsigned ceiling,death_phase;uint32_t death_cursor; + bool died,victory,demo; +} wl_present_snapshot; +void WL_PresentReset(void); +void WL_PresentAllocated(unsigned slot); +void WL_PresentCapture(uint64_t tick); +/* Writes only caller-owned presentation storage; snapshots remain immutable. */ +bool WL_PresentSample(uint64_t now_ns,wl_present_snapshot *out); +const wl_present_snapshot *WL_PresentCurrent(void); +double WL_PresentAngle(double previous,double current,double alpha); +#endif diff --git a/src/engine/WL_PROFILE.h b/src/engine/WL_PROFILE.h new file mode 100644 index 00000000..4fedef16 --- /dev/null +++ b/src/engine/WL_PROFILE.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_PROFILE_H +#define WL_PROFILE_H +/* Optional benchmark instrumentation; absent from normal and test builds. */ +#ifdef WOLF3D_BENCHMARK +#include +typedef struct { + uint64_t rays,sprites,capture,sample,convert,upload,present,empty_queues; +} wl_profile; +extern wl_profile WL_Profile; +uint64_t WL_ProfileNow(void); +#define WL_PROFILE_BEGIN(name) uint64_t name=WL_ProfileNow() +#define WL_PROFILE_END(field,name) (WL_Profile.field+=WL_ProfileNow()-(name)) +#else +#define WL_PROFILE_BEGIN(name) +#define WL_PROFILE_END(field,name) ((void)0) +#endif +#endif diff --git a/src/engine/WL_RENDER.c b/src/engine/WL_RENDER.c new file mode 100644 index 00000000..ce0f9d94 --- /dev/null +++ b/src/engine/WL_RENDER.c @@ -0,0 +1,271 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Native indexed presentation using the same ray intersections as DOS. The + authoritative DOS pass runs unchanged; this pass has no simulation writes. */ +#include "WL_RENDER.h" +#include "WL_DEMO.h" +#include "ID_CA.h" +#include "ID_FILE.h" +#include "ID_PM.h" +#include "ID_VL.h" +#include "WL_PROFILE.h" +#include +#include +#include +bool WL_RenderResolution(unsigned w,unsigned h) +{ return w>=320 && h>=200 && w<=WL_TARGET_MAX_WIDTH && h<=WL_TARGET_MAX_HEIGHT; } +void WL_RenderContent(unsigned width,unsigned height,unsigned *x,unsigned *w) +{ + uint64_t scaled=(uint64_t)height*4/3; + unsigned content=scaled>width?width:(unsigned)scaled; + if(x) *x=(width-content)/2; + if(w) *w=content; +} +typedef struct { + wl_render_target *target; + int x,y,w,h; + double focal; + int32_t camera_x,camera_y; + uint32_t sine,cosine; + int32_t *depth; + void (*service)(void); + double angle;const wl_present_snapshot *snapshot;wl_ray_world rayworld; +} view; +static void Project(const view *v,int32_t x,int32_t y,int32_t bias,int32_t *nx,int32_t *ny) +{ + int32_t dx=x-v->camera_x,dy=y-v->camera_y; + *nx=FixedByFrac(dx,v->cosine)-FixedByFrac(dy,v->sine)-bias; + *ny=FixedByFrac(dy,v->cosine)+FixedByFrac(dx,v->sine); +} +/* Retain original two-half anchoring and transparency posts. Index zero can + be opaque. Square DOS texels become 1:1.2 on the corrected 4:3 canvas. */ +static bool Shape(const view *v,double center,unsigned sprite,double width,int32_t distance,bool overlay) +{ + if(width<=0 || width>1000000 || center+width<0 || center-width>v->w) return true; + w3r_byte pixels[4096],opaque[4096]; + if(!PM_DecodeSprite(sprite,pixels,opaque)) return false; + const w3r_byte *page=PM_GetPage(PMSpriteStart+sprite,NULL); + int first=(int)CA_LE16(page),last=(int)CA_LE16(page+2); + double height=width*1.2,top=((double)v->h-height)/2; + int row_start[64],row_end[64]; + for(int sy=0;sy<64;++sy) { + int y0=(int)floor(top+sy*height/64),y1=(int)floor(top+(sy+1)*height/64); + row_start[sy]=y0<0?0:y0;row_end[sy]=y1>v->h?v->h:y1; + } + for(int half=0;half<2;++half) { + double cursor=center; + int start=half?(first<32?32:first):31,stop=half?last:first; + for(int sx=start;half?sx<=stop:sx>=stop;sx+=half?1:-1) { + if(v->service && sx%4==0) v->service(); + double span=(sx+1)*width/64-sx*width/64; + if(!half) cursor-=span; + int x0=(int)floor(cursor),x1=(int)floor(cursor+span); + if(half) cursor+=span; + if(x0<0) x0=0; + if(x1>v->w) x1=v->w; + /* Clip once per horizontal run, then fill texel rectangles in + row order. Keep the original floor/half anchoring exactly. */ + for(int x=x0;xdepth[x]<=distance) ++x; + int run=x; + while(xdepth[x]>distance)) ++x; + if(run==x) continue; + for(int sy=0;sy<64;++sy) { + if(!opaque[sy*64+sx]) continue; + for(int y=row_start[sy];ytarget->pixels+(size_t)(v->y+y)*v->target->stride+ + (unsigned)(v->x+run),pixels[sy*64+sx],(size_t)(x-run)); + } + } + } + } + return true; +} +typedef struct { int32_t depth;double center,width;unsigned shape; } render_sprite; +static bool Scene(view *v) +{ + WL_PROFILE_BEGIN(ray_start); + unsigned ceiling=v->snapshot?v->snapshot->ceiling:WL_CeilingColor(); + /* Clear sky/floor in contiguous rows; only wall spans need column writes. */ + for(int y=0;yh;++y) { + if(v->service && y%32==0) v->service(); + memset(v->target->pixels+(size_t)(v->y+y)*v->target->stride+(unsigned)v->x, + yh/2?(int)ceiling:0x19,(size_t)v->w); + } + for(int x=0;xw;++x) { + if(v->service && x%16==0) v->service(); + /* Same field of view as the DOS viewport, sampled at each new column. + Keep the original 0.1-degree tangent table and intersection rules. */ + double offset=((double)v->w/2-0.5-x)/v->focal; + int angle=(int)(v->angle*10)+(int)(atan(offset)*1800/3.141592657); + rayhit hit;if(!(v->snapshot?WL_RenderRayWorld(angle,&hit,&v->rayworld):WL_RenderRay(angle,&hit))) return false; + int32_t nx,ny;Project(v,hit.x,hit.y,0,&nx,&ny);(void)ny; + if(nxdepth[x]=nx; + double height=65536*v->focal/(double)nx*1.2,top=((double)v->h-height)/2; + int start=(int)ceil(top),end=(int)ceil(top+height); + if(start<0) start=0; + if(end>v->h) end=v->h; + size_t bytes;const w3r_byte *page=PM_GetPage(hit.page,&bytes); + if(!page || bytes!=4096) return CA_Fail("Invalid high-resolution wall page"); + double texel_scale=64.0/height; + for(int y=start;y63) row=63; + v->target->pixels[(size_t)(v->y+y)*v->target->stride+(unsigned)(v->x+x)]=page[hit.column*64+(unsigned)row]; + } + } + WL_PROFILE_END(rays,ray_start); + WL_PROFILE_BEGIN(sprite_start); + render_sprite sprites[MAXSTATS+MAXACTORS]; + unsigned count=0; + for(unsigned i=0;i<(v->snapshot?v->snapshot->static_count:statcount);++i) { + const statobj_t *o=v->snapshot?&v->snapshot->statics[i]:&statobjlist[i];if(o->shapenum<0) continue; + int32_t nx,ny;Project(v,o->tilex*TILEGLOBAL+32768,o->tiley*TILEGLOBAL+32768,0x2000,&nx,&ny); + if(nxw/2+(double)ny*v->focal/nx; + sprites[count].width=65536*v->focal/nx;sprites[count++].shape=(unsigned)o->shapenum; + } + if(v->snapshot) { + for(unsigned k=0;ksnapshot->count;++k) { + const wl_present_actor *o=&v->snapshot->actors[v->snapshot->order[k]]; + if(!o->shape) continue; + int32_t nx,ny;Project(v,o->x,o->y,ACTORSIZE,&nx,&ny);if(nxshape; + if(o->rotate) { + int original_scale=(VIEWWIDTH/2)*(FOCALLENGTH+MINDIST)/32768; + int screen=VIEWWIDTH/2-1+(int)((int64_t)ny*original_scale/nx); + int viewangle=(int)v->angle+(VIEWWIDTH/2-1-screen)/8; + int angle=(viewangle-180)-(int)o->facing+ANGLES/16; + angle%=ANGLES;if(angle<0) angle+=ANGLES; + shape+=o->rotate==2?4*(angle/(ANGLES/2)):angle/(ANGLES/8); + } + sprites[count++]=(render_sprite){nx,(double)v->w/2+(double)ny*v->focal/nx,65536*v->focal/nx,(unsigned)shape}; + } + } else + for(const objtype *o=player.next;o;o=o->next) { + if(!o->state || !o->state->shapenum) continue; + int32_t nx,ny;Project(v,o->x,o->y,ACTORSIZE,&nx,&ny); + if(nxstate->shapenum; + if(shape<0) shape=o->temp1; + if(o->state->rotate) shape+=CalcRotate(©); + if(count>=MAXSTATS+MAXACTORS) return CA_Fail("High-resolution sprite list overflow"); + sprites[count].depth=nx;sprites[count].center=(double)v->w/2+(double)ny*v->focal/nx; + sprites[count].width=65536*v->focal/nx;sprites[count++].shape=(unsigned)shape; + } + /* Stable far-to-near order; transparent posts preserve nearer artwork. */ + for(unsigned i=1;isnapshot?v->snapshot->died:gamestate.died) && !(v->snapshot?v->snapshot->victory:gamestate.victoryflag) && !Shape(v,(double)v->w/2,weapons[v->snapshot?v->snapshot->weapon:(unsigned)gamestate.weapon]+(v->snapshot?v->snapshot->weapon_frame:(unsigned)gamestate.weaponframe),(double)v->h/1.2,0,true)) return false; + bool ok=!(v->snapshot?v->snapshot->demo:Demo_Active()) || Shape(v,(double)v->w/2,SPR_DEMO,(double)v->h/1.2,0,true); + WL_PROFILE_END(sprites,sprite_start);return ok; +} +static void Bar(wl_render_target *t,int x,int y,int w,int h,w3r_byte color) +{ + if(x<0) { w+=x;x=0; }if(y<0) { h+=y;y=0; } + if(x+w>(int)t->width) w=(int)t->width-x; + if(y+h>(int)t->height) h=(int)t->height-y; + if(w<=0 || h<=0) return; + for(int row=0;rowpixels+(size_t)(y+row)*t->stride+(unsigned)x,color,(size_t)w); +} +/* Replay the original fizzle polynomial up to its current cursor. This is + presentation data only: never advance the game's cursor, RNG or timer. + Mapping the mask to the native viewport keeps its geometry throughout death. */ +static void DeathFizzle(const view *v,unsigned phase,uint32_t cursor) +{ + if(phase<2) return; + if(phase==3) { Bar(v->target,v->x,v->y,v->w,v->h,4);return; } + uint8_t mask[320*160/8]={0};uint32_t seed=1; + for(unsigned steps=0;seed!=cursor && steps<131071;++steps) { + unsigned x=seed>>8,y=(seed-1)&255U; + if(x>1)^((seed&1U)?UINT32_C(0x12000):0U); + } + for(int y=0;yh;++y) { + if(v->service && y%16==0) v->service(); + unsigned row=(unsigned)y*VIEWHEIGHT/(unsigned)v->h; + for(int x=0;xw;++x) { + unsigned column=(unsigned)x*VIEWWIDTH/(unsigned)v->w,bit=row*320+column; + if(mask[bit/8]&(1U<<(bit%8))) v->target->pixels[(size_t)(v->y+y)*v->target->stride+(unsigned)(v->x+x)]=4; + } + } +} +bool WL_RenderSnapshot(wl_render_target *target,int32_t *depth,size_t columns,bool world,unsigned aw,unsigned ah,const wl_present_snapshot *snapshot,void (*service)(void)) +{ + if(!WL_TargetValid(target) || !WL_RenderResolution(target->width,target->height) || !depth || columnswidth) + return CA_Fail("Invalid high-resolution target/depth capacity"); + if(snapshot) { + if(!(snapshot->camera.angle>=0 && snapshot->camera.angle<360) || snapshot->count>MAXACTORS || snapshot->static_count>MAXSTATS || snapshot->door_count>64 || snapshot->ceiling>255 || snapshot->death_phase>3 || snapshot->weapon>3 || snapshot->weapon_frame>4 || snapshot->camera.x<0 || snapshot->camera.y<0 || snapshot->camera.x>64*TILEGLOBAL || snapshot->camera.y>64*TILEGLOBAL || snapshot->push_offset<0 || snapshot->push_offset>65535) + return CA_Fail("Invalid presentation snapshot"); + for(unsigned i=0;icount;++i) { + if(snapshot->order[i]>=MAXACTORS) return CA_Fail("Invalid snapshot actor slot"); + const wl_present_actor *a=&snapshot->actors[snapshot->order[i]]; + if(!(a->facing>=0 && a->facing<360) || a->dir<0 || a->dir>8 || a->shape<0 || a->shape>65535 || a->x< -TILEGLOBAL || a->y< -TILEGLOBAL || a->x>65*TILEGLOBAL || a->y>65*TILEGLOBAL) return CA_Fail("Invalid snapshot actor"); + } + } + if(snapshot) for(unsigned i=0;istatic_count;++i) + if(snapshot->statics[i].tilex<0 || snapshot->statics[i].tilex>=64 || snapshot->statics[i].tiley<0 || snapshot->statics[i].tiley>=64) return CA_Fail("Invalid snapshot static"); + wl_rectangle scene,ui; + if(!WL_AspectFit(target->width,target->height,aw,ah,&scene) || scene.width<4 || scene.height<3 || + !WL_AspectFit(scene.width,scene.height,4,3,&ui)) return CA_Fail("Invalid rendering aspect"); + ui.x+=scene.x;ui.y+=scene.y; + if(!WL_TargetClear(target,0)) return false; + bool scene_active=world && CA_Map() && (!(snapshot?snapshot->victory:gamestate.victoryflag) || (snapshot?snapshot->died:gamestate.died)); + /* Original artwork remains centered and aspect-correct. The plain teal + border expands around the new viewport rather than retaining an old + 4:3 bevel behind widescreen geometry. */ + /* Fill the full widescreen playfield with the original teal border color. + The central 4:3 status artwork below is drawn over this background; + do not leave black side gutters beneath the playfield. */ + if(scene_active) Bar(target,(int)scene.x,(int)scene.y,(int)scene.width,(int)scene.height,127); + for(unsigned y=scene_active?ui.height*4/5:0;ypixels[(size_t)(ui.y+y)*target->stride+ui.x+x]=framebuffer[(size_t)(y*200/ui.height)*320+x*320/ui.width]; + } + if(!scene_active) return true; + view v={0};v.target=target;v.depth=depth;v.service=service; + v.x=(int)(scene.x+(unsigned)VIEWX*scene.width/320);v.y=(int)(scene.y+(unsigned)VIEWY*scene.height/200); + v.w=(int)(((unsigned)VIEWX+VIEWWIDTH)*scene.width/320)-(v.x-(int)scene.x); + v.h=(int)(((unsigned)VIEWY+VIEWHEIGHT)*scene.height/200)-(v.y-(int)scene.y); + /* Fixed vertical framing: horizontal visibility grows with aspect. */ + v.focal=(double)scene.height*4/3*(double)VIEWWIDTH/320/2*(FOCALLENGTH+MINDIST)/32768; + v.snapshot=snapshot;v.angle=snapshot?snapshot->camera.angle:player.angle; + int angle=(int)v.angle;double fraction=v.angle-angle; + uint32_t values[2]; + for(unsigned i=0;i<2;++i) { + uint32_t a=sintable[angle+(int)i*90],b=sintable[(angle+1)%360+(int)i*90]; + int32_t sa=(a&0x80000000U)?-(int32_t)(a&0x7fffffffU):(int32_t)a; + int32_t sb=(b&0x80000000U)?-(int32_t)(b&0x7fffffffU):(int32_t)b; + int32_t value=(int32_t)(sa+((double)sb-sa)*fraction); + values[i]=value<0?0x80000000U|(uint32_t)(-value):(uint32_t)value; + } + v.sine=snapshot?values[0]:sintable[player.angle];v.cosine=snapshot?values[1]:sintable[player.angle+90]; + v.camera_x=(snapshot?snapshot->camera.x:player.x)-FixedByFrac(FOCALLENGTH,v.cosine); + v.camera_y=(snapshot?snapshot->camera.y:player.y)+FixedByFrac(FOCALLENGTH,v.sine); + v.rayworld=(wl_ray_world){v.camera_x,v.camera_y,v.sine,v.cosine,snapshot}; + int bx=(int)((ui.width+319)/320),by=(int)((ui.height+199)/200); + Bar(target,v.x-bx,v.y-by,v.w+2*bx,by,0); + Bar(target,v.x-bx,v.y+v.h,v.w+2*bx,by,125); + Bar(target,v.x-bx,v.y-by,bx,v.h+2*by,0); + Bar(target,v.x+v.w,v.y-by,bx,v.h+2*by,125); + Bar(target,v.x-bx,v.y+v.h,bx,by,124); + uint32_t cursor=0;unsigned phase=GameDeathPresentation(&cursor); + if(snapshot) { phase=snapshot->death_phase;cursor=snapshot->death_cursor; } + if(phase!=3 && !Scene(&v)) return false; + DeathFizzle(&v,phase,cursor);return true; +} + +bool WL_RenderFrameAspect(wl_render_target *target,int32_t *depth,size_t columns,bool world,unsigned aw,unsigned ah,void (*service)(void)) +{ return WL_RenderSnapshot(target,depth,columns,world,aw,ah,NULL,service); } +bool WL_RenderFrame(wl_render_target *target,int32_t *depth,size_t columns,bool world,void (*service)(void)) +{ return WL_RenderFrameAspect(target,depth,columns,world,4,3,service); } diff --git a/src/engine/WL_RENDER.h b/src/engine/WL_RENDER.h new file mode 100644 index 00000000..cfc8598b --- /dev/null +++ b/src/engine/WL_RENDER.h @@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_RENDER_H +#define WL_RENDER_H +#include "WL_RENDER_TARGET.h" +#include "WL_DEF.h" +#include "WL_ASPECT.h" +#include "WL_PRESENT.h" +typedef struct { int32_t x,y;uint32_t sine,cosine;const wl_present_snapshot *scene; } wl_ray_world; +bool WL_RenderRayWorld(int angle,rayhit *hit,const wl_ray_world *world); +/* Presentation only. Never changes spotvis, actors, inventory or RNG. */ +bool WL_RenderRay(int angle,rayhit *hit); +unsigned WL_CeilingColor(void); +uint64_t WL_RenderSerial(void); +bool WL_RenderResolution(unsigned width,unsigned height); +/* Centered 4:3 image within the selected output canvas. */ +void WL_RenderContent(unsigned width,unsigned height,unsigned *x,unsigned *w); +/* Optional main-thread service runs between bounded rendering batches (audio). + NULL keeps the pass entirely read-only. Caller supplies persistent target and per-column depth storage. */ +bool WL_RenderSnapshot(wl_render_target *target,int32_t *depth,size_t columns,bool world, + unsigned aspect_width,unsigned aspect_height,const wl_present_snapshot *snapshot,void (*service)(void)); +bool WL_RenderFrameAspect(wl_render_target *target,int32_t *depth,size_t columns,bool world, + unsigned aspect_width,unsigned aspect_height,void (*service)(void)); +bool WL_RenderFrame(wl_render_target *target,int32_t *depth,size_t columns,bool world,void (*service)(void)); +#endif diff --git a/src/engine/WL_RENDER_TARGET.c b/src/engine/WL_RENDER_TARGET.c new file mode 100644 index 00000000..35ee35f7 --- /dev/null +++ b/src/engine/WL_RENDER_TARGET.c @@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "WL_RENDER_TARGET.h" +#include +#include +#include +bool WL_TargetValid(const wl_render_target *t) +{ + return t && t->pixels && t->width && t->height && + t->width<=WL_TARGET_MAX_WIDTH && t->height<=WL_TARGET_MAX_HEIGHT && + t->stride>=t->width && t->stride<=WL_TARGET_MAX_WIDTH*2 && + (size_t)t->stride<=SIZE_MAX/t->height && + (size_t)t->stride*t->height<=t->capacity; +} +bool WL_TargetInit(wl_render_target *target,uint8_t *pixels,size_t capacity, + unsigned width,unsigned height,unsigned stride) +{ + wl_render_target candidate={pixels,width,height,stride,capacity}; + if(!target || !WL_TargetValid(&candidate)) return false; + *target=candidate;return true; +} +bool WL_TargetClear(const wl_render_target *target,uint8_t color) +{ + if(!WL_TargetValid(target)) return false; + for(unsigned y=0;yheight;++y) + memset(target->pixels+(size_t)y*target->stride,color,target->width); + return true; +} +bool WL_TargetPixel(const wl_render_target *target,unsigned x,unsigned y,uint8_t color) +{ + if(!WL_TargetValid(target) || x>=target->width || y>=target->height) return false; + target->pixels[(size_t)y*target->stride+x]=color;return true; +} diff --git a/src/engine/WL_RENDER_TARGET.h b/src/engine/WL_RENDER_TARGET.h new file mode 100644 index 00000000..ef27baa6 --- /dev/null +++ b/src/engine/WL_RENDER_TARGET.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_RENDER_TARGET_H +#define WL_RENDER_TARGET_H +#include +#include +#include +/* A renderer-owned indexed surface. Classic continues to use its original + fixed 320x200 framebuffer. The high-resolution renderer may use this type + without requiring game simulation or SDL to know the output dimensions. */ +typedef struct { + uint8_t *pixels; + unsigned width,height,stride; + size_t capacity; +} wl_render_target; +#define WL_TARGET_MAX_WIDTH 4096U +#define WL_TARGET_MAX_HEIGHT 2160U +bool WL_TargetValid(const wl_render_target *target); +/* Does not allocate or own pixels. Stride is in pixels, not bytes. */ +bool WL_TargetInit(wl_render_target *target,uint8_t *pixels,size_t capacity, + unsigned width,unsigned height,unsigned stride); +bool WL_TargetClear(const wl_render_target *target,uint8_t color); +bool WL_TargetPixel(const wl_render_target *target,unsigned x,unsigned y,uint8_t color); +#endif diff --git a/src/engine/WL_SAVE.c b/src/engine/WL_SAVE.c new file mode 100644 index 00000000..3b037c9a --- /dev/null +++ b/src/engine/WL_SAVE.c @@ -0,0 +1,363 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Native counterpart of WL_MAIN.C SaveTheGame/LoadTheGame. Version 1 is + explicit little-endian fields, not the DOS structure/pointer dump. */ +#include "WL_SAVE.h" +#include "ID_CA.h" +#include "ID_FILE.h" +#include "ID_PM.h" +#include "ID_SD.h" +#include "ID_US_1.h" +#include "ID_IN.h" +#include "platform/data_file.h" +#include "platform/save_file.h" +#include +#include +#include +#define SAVE_HEADER 96U +#define SAVE_LIMIT (256U*1024U) +#define SAVE_STATE(name) extern statetype name; +#include "WL_SAVE_STATES.inc" +#undef SAVE_STATE +static statetype *const states[]={NULL, +#define SAVE_STATE(name) &name, +#include "WL_SAVE_STATES.inc" +#undef SAVE_STATE +}; +unsigned Save_StateCount(void) { return (unsigned)(sizeof(states)/sizeof(states[0])); } +statetype *Save_State(unsigned id) { return id=sizeof(directory)-32) return CA_Fail("Save directory unavailable/too long"); + (void)strcpy(directory,path);return true; +} +static bool Path(unsigned slot,char result[4096]) +{ + if(slot>=SAVE_SLOTS || !*directory) return CA_Fail("Save storage unavailable or invalid slot"); + int n=snprintf(result,4096,"%s/slot%u.w3s",directory,slot+1); + return n>0 && n<4096; +} +static uint32_t CRC(uint32_t crc,const void *data,size_t size) +{ + const uint8_t *p=data; + while(size--) { + crc^=*p++; + for(unsigned i=0;i<8;++i) crc=(crc>>1)^((crc&1)?UINT32_C(0xedb88320):0); + } + return crc; +} +static void Put32(uint8_t *p,uint32_t v) { for(unsigned i=0;i<4;++i) p[i]=(uint8_t)(v>>(i*8)); } +static bool Identity(uint32_t ids[3]) +{ + static const char *const names[]={"MAPHEAD.WL6","GAMEMAPS.WL6","VSWAP.WL6"}; + for(unsigned i=0;i<3;++i) { + FILE *file=CA_OpenDataFile(CA_DataDirectory(),names[i]); + if(!file) return CA_Fail("Cannot identify save resources: %s",names[i]); + uint8_t buffer[8192];size_t n,total=0;uint32_t crc=UINT32_MAX; + while((n=fread(buffer,1,sizeof(buffer),file))!=0) { total+=n;if(total>32U*1024U*1024U) break;crc=CRC(crc,buffer,n); } + bool ok=!ferror(file) && total && total<=32U*1024U*1024U;(void)fclose(file); + if(!ok) return CA_Fail("Cannot read save resource identity"); + ids[i]=~crc; + } + return true; +} +typedef struct { + gametype game;levelratio_t ratios[8];objtype player,actors[MAXACTORS]; + bool used[MAXACTORS];unsigned count,stat_count,door_count,rng,mode; + unsigned state[MAXACTORS+1];int next[MAXACTORS+1],at[64][64]; + statobj_t stats[MAXSTATS];doorobj_t doors[64]; + uint8_t walls[64][64];int areas[64][64];bool solid[64][64],push[64][64],noise; + unsigned wall_state,wall_pos;int wall_x,wall_y,wall_dir,thrust; + save_controls controls;maptype map; +} snapshot; +typedef struct { uint8_t *data;size_t pos,size;bool read,ok; } codec; +static uint32_t Word(codec *c,uint32_t v) +{ + if(!c->ok || c->pos>c->size || c->size-c->pos<4) { c->ok=false;return 0; } + if(c->read) v=CA_LE32(c->data+c->pos);else Put32(c->data+c->pos,v); + c->pos+=4;return v; +} +static void Integer(codec *c,int *v) +{ + uint32_t n=Word(c,(uint32_t)*v); + if(c->read) *v=n<=INT32_MAX?(int)n:-(int)(UINT32_MAX-n)-1; +} +static void Unsigned(codec *c,unsigned *v) { *v=(unsigned)Word(c,(uint32_t)*v); } +static void Boolean(codec *c,bool *v) { uint32_t n=Word(c,*v?1:0);if(n>1) c->ok=false;*v=n!=0; } +#define GAME_INTS(X) X(health) X(ammo) X(lives) X(keys) X(score) X(nextextra) X(weapon) X(bestweapon) X(chosenweapon) X(attackframe) X(weaponframe) X(attackcount) X(faceframe) X(killcount) X(killtotal) X(treasurecount) X(treasuretotal) X(episode) X(mapon) X(difficulty) X(oldscore) X(secretcount) X(secrettotal) X(killx) X(killy) +#define ACTOR_INTS(X) X(x) X(y) X(angle) X(tilex) X(tiley) X(dir) X(obclass) X(areanumber) X(hitpoints) X(ticcount) X(temp1) X(temp2) X(viewx) X(viewheight) X(speed) X(distance) X(transx) X(transy) +static void Actor(codec *c,objtype *a) +{ +#define FIELD(n) Integer(c,&a->n); + ACTOR_INTS(FIELD) +#undef FIELD + Unsigned(c,&a->flags);Boolean(c,&a->active); +} +static void Ratio(codec *c,levelratio_t *r) +{ + Unsigned(c,&r->kill);Unsigned(c,&r->secret);Unsigned(c,&r->treasure);Unsigned(c,&r->seconds);Unsigned(c,&r->par);Integer(c,&r->bonus); +} +static void Payload(codec *c,snapshot *s) +{ +#define FIELD(n) Integer(c,&s->game.n); + GAME_INTS(FIELD) +#undef FIELD + s->game.TimeCount=Word(c,s->game.TimeCount);Boolean(c,&s->game.died);Boolean(c,&s->game.victoryflag); + for(unsigned i=0;i<8;++i) Ratio(c,&s->ratios[i]); + Unsigned(c,&s->rng);Unsigned(c,&s->mode);Unsigned(c,&s->count);Unsigned(c,&s->stat_count);Unsigned(c,&s->door_count); + if(s->count>MAXACTORS || s->stat_count>MAXSTATS || s->door_count>64) { c->ok=false;return; } + Actor(c,&s->player);Unsigned(c,&s->state[0]);Integer(c,&s->next[0]); + for(unsigned i=0;icount;++i) { + Boolean(c,&s->used[i]); + if(s->used[i]) { Actor(c,&s->actors[i]);Unsigned(c,&s->state[i+1]);Integer(c,&s->next[i+1]); } + } + for(unsigned i=0;istat_count;++i) { + statobj_t *o=&s->stats[i];Integer(c,&o->tilex);Integer(c,&o->tiley);Integer(c,&o->shapenum); + unsigned item=(unsigned)o->itemnumber;Unsigned(c,&item);o->itemnumber=(stat_t)item;Boolean(c,&o->bonus); + } + for(unsigned i=0;idoor_count;++i) { + doorobj_t *d=&s->doors[i];Unsigned(c,&d->x);Unsigned(c,&d->y);Unsigned(c,&d->lock);Boolean(c,&d->vertical); + unsigned action=(unsigned)d->action,position=d->position;Unsigned(c,&action);Unsigned(c,&position); + if(action>3 || position>65535) c->ok=false; + d->action=(dooraction)action;d->position=(uint16_t)position;Unsigned(c,&d->ticcount); + } + Unsigned(c,&s->wall_state);Unsigned(c,&s->wall_pos);Integer(c,&s->wall_x);Integer(c,&s->wall_y);Integer(c,&s->wall_dir); + for(unsigned x=0;x<64;++x) for(unsigned y=0;y<64;++y) { + unsigned tile=s->walls[x][y];Unsigned(c,&tile);if(tile>255) c->ok=false;s->walls[x][y]=(uint8_t)tile; + Integer(c,&s->areas[x][y]);Integer(c,&s->at[x][y]);Boolean(c,&s->solid[x][y]);Boolean(c,&s->push[x][y]); + } + Boolean(c,&s->noise);Integer(c,&s->thrust);Integer(c,&s->controls.facecount);Integer(c,&s->controls.anglefrac); + Boolean(c,&s->controls.attackheld);Boolean(c,&s->controls.gotgatgun); +} +static int Reference(const objtype *o) +{ + if(!o) return -1; + for(unsigned i=0;igame=gamestate;memcpy(s->ratios,LevelRatios,sizeof(s->ratios));s->player=player; + s->count=objcount;s->stat_count=statcount;s->door_count=doornum;s->rng=US_RndIndex();s->mode=SD_DigitizedMode()?1U:0U; + s->state[0]=Save_StateID(player.state);s->next[0]=Reference(player.next); + for(unsigned i=0;iused[i]=Save_ActorAllocated(i))) { + s->actors[i]=objlist[i];s->state[i+1]=Save_StateID(objlist[i].state);s->next[i+1]=Reference(objlist[i].next); + } + memcpy(s->stats,statobjlist,sizeof(s->stats));memcpy(s->doors,doorobjlist,sizeof(s->doors)); + memcpy(s->walls,tilemap,sizeof(s->walls));memcpy(s->areas,areaMap,sizeof(s->areas)); + memcpy(s->solid,staticblock,sizeof(s->solid));memcpy(s->push,pushable,sizeof(s->push)); + for(unsigned x=0;x<64;++x) for(unsigned y=0;y<64;++y) s->at[x][y]=Reference(actorat[x][y]); + s->wall_state=pwallstate;s->wall_pos=pwallpos;s->wall_x=pwallx;s->wall_y=pwally;s->wall_dir=pwalldir; + s->noise=madenoise;s->thrust=thrustspeed;Save_GetCombat(&s->controls);s->controls.anglefrac=Save_GetAngleFraction(); +} +static bool Coordinate(int v) { return v>=0 && v<64; } +static bool Position(int v) { return v>=0 && v<64*TILEGLOBAL; } +static bool ValidActor(const objtype *o,bool isplayer) +{ + return Coordinate(o->tilex) && Coordinate(o->tiley) && Position(o->x) && Position(o->y) && + o->angle>=0 && o->angle<360 && o->dir>=0 && o->dir<=nodir && o->obclass>=0 && o->obclass<=rocketobj && + (isplayer || o->obclass>=inertobj) && o->areanumber>=0 && o->areanumber<37 && !(o->flags&~253U) && + o->speed>=0 && o->speed<=65536 && o->distance>=-65536 && o->distance<=64*TILEGLOBAL && + o->hitpoints>=-100000 && o->hitpoints<=100000 && o->ticcount>=-10000 && o->ticcount<=10000 && + o->temp1>=-65536 && o->temp1<=1000000 && o->temp2>=-65536 && o->temp2<=1000000 && + o->viewx>=-1000000 && o->viewx<=1000000 && o->viewheight>=0 && o->viewheight<=1000000 && + o->transx>=-64*TILEGLOBAL && o->transx<=64*TILEGLOBAL && o->transy>=-64*TILEGLOBAL && o->transy<=64*TILEGLOBAL; +} +/* Match SetupGameLevel's reachable-space enclosure rule. Unused floor at an + outer edge exists in original maps, so requiring every edge cell to be a + wall would reject legitimate data. Closed doors remain traversable here. */ +static bool ValidMap(const snapshot *s) +{ + if(s->player.tilex!=s->player.x/TILEGLOBAL || s->player.tiley!=s->player.y/TILEGLOBAL || + s->player.xplayer.yplayer.x>=64*TILEGLOBAL-MINDIST || s->player.y>=64*TILEGLOBAL-MINDIST) return false; + unsigned tile=s->walls[s->player.tilex][s->player.tiley]; + if(tile && tile!=64 && (tile&0xc0)!=0x80) return false; + bool seen[64][64]={{false}};unsigned queue[4096],head=0,tail=0; + queue[tail++]=(unsigned)(s->player.tiley*64+s->player.tilex);seen[s->player.tilex][s->player.tiley]=true; + static const int dx[]={1,0,-1,0},dy[]={0,1,0,-1}; + while(headwalls[nx][ny]; + if(seen[nx][ny] || (tile && tile!=64 && (tile&0xc0)!=0x80)) continue; + seen[nx][ny]=true;queue[tail++]=(unsigned)(ny*64+nx); + } + } + return true; +} +static bool Valid(const snapshot *s) +{ + const gametype *g=&s->game; + if(g->episode<0 || g->episode>=6 || g->mapon<0 || g->mapon>=10 || g->difficulty<0 || g->difficulty>=4 || + g->health<=0 || g->health>100 || g->ammo<0 || g->ammo>99 || g->lives<0 || g->lives>9 || g->keys<0 || g->keys>15 || + g->weapon<0 || g->weapon>3 || g->bestweaponweapon || g->bestweapon>3 || g->chosenweapon<0 || g->chosenweapon>g->bestweapon || + g->attackframe<0 || g->attackframe>4 || g->weaponframe<0 || g->weaponframe>4 || g->attackcount<0 || g->attackcount>12 || + g->faceframe<0 || g->faceframe>2 || g->score<0 || g->score>100000000 || g->nextextra<=g->score || g->nextextra>100040000 || + g->oldscore<0 || g->oldscore>100000000 || g->died || g->victoryflag || + !Position(g->killx) || !Position(g->killy) || s->rng>255 || s->mode>1 || + s->count>MAXACTORS || s->stat_count>MAXSTATS || s->door_count>64 || + s->controls.facecount<0 || s->controls.facecount>256 || s->controls.anglefrac<=-20 || s->controls.anglefrac>=20 || + s->thrust<0 || s->thrust>100000 || !ValidActor(&s->player,true) || s->state[0]!=0) return false; + int counts[]={g->killcount,g->killtotal,g->secretcount,g->secrettotal,g->treasurecount,g->treasuretotal}; + for(unsigned i=0;i<6;++i) if(counts[i]<0 || counts[i]>4096) return false; + for(unsigned i=0;i<8;++i) { + const levelratio_t *r=&s->ratios[i]; + if(r->kill>10000 || r->secret>10000 || r->treasure>10000 || r->seconds>5940 || r->par>10000 || r->bonus<0 || r->bonus>10000000) return false; + } + bool visited[MAXACTORS]={false};int next=s->next[0]; + while(next!=-1) { + if(next<0 || (unsigned)next>=s->count || !s->used[next] || visited[next]) return false; + visited[next]=true;next=s->next[next+1]; + } + for(unsigned i=0;icount;++i) { + if(s->used[i]!=visited[i]) return false; + if(s->used[i] && (!ValidActor(&s->actors[i],false) || !s->state[i+1] || s->state[i+1]>=Save_StateCount() || + (s->actors[i].distance<0 && (unsigned)(-s->actors[i].distance-1)>=s->door_count))) return false; + } + if(s->wall_state>255 || s->wall_pos>63) return false; + if(s->wall_state && (!Coordinate(s->wall_x) || !Coordinate(s->wall_y) || s->wall_x==0 || s->wall_x==63 || + s->wall_y==0 || s->wall_y==63 || s->wall_dir<0 || s->wall_dir>6 || (s->wall_dir&1))) return false; + for(unsigned x=0;x<64;++x) for(unsigned y=0;y<64;++y) { + unsigned tile=s->walls[x][y];int ref=s->at[x][y]; + if(s->areas[x][y]<0 || s->areas[x][y]>=37 || ref< -1 || (ref>=0 && ((unsigned)ref>=s->count || !s->used[ref]))) return false; + if((tile&0xc0)==0x80 && (tile&63)>=s->door_count) return false; + if((tile&0xc0)==0xc0 && (!s->wall_state || x!=(unsigned)s->wall_x || y!=(unsigned)s->wall_y || !(tile&63))) return false; + } + for(unsigned i=0;idoor_count;++i) { + const doorobj_t *d=&s->doors[i]; + if(d->x<1 || d->x>62 || d->y<1 || d->y>62 || d->lock>5 || (unsigned)d->action>3 || d->ticcount>65535 || + s->walls[d->x][d->y]!=(128U+i)) return false; + } + for(unsigned i=0;istat_count;++i) { + const statobj_t *o=&s->stats[i]; + if(!Coordinate(o->tilex) || !Coordinate(o->tiley) || o->shapenum< -1 || o->shapenum>4095 || (unsigned)o->itemnumber>bo_spear) return false; + } + return ValidMap(s); +} +static bool Description(const char *p) +{ + if(!p || !*p) return false; + for(unsigned i=0;i126) return false; } + return false; +} +static save_status Header(const uint8_t *h,size_t file_size,unsigned slot,save_info *info) +{ + if(memcmp(h,"W3RSAVE",8)) return SAVE_CORRUPT; + info->version=CA_LE32(h+8); + if(info->version!=SAVE_VERSION) return SAVE_UNSUPPORTED; + if(CA_LE32(h+12)!=SAVE_HEADER || CA_LE32(h+16)>SAVE_LIMIT || + SAVE_HEADER+(size_t)CA_LE32(h+16)!=file_size || CA_LE32(h+20)!=slot || + CA_LE32(h+28)>5 || CA_LE32(h+32)>9 || CA_LE32(h+36)>3 || !Description((const char *)h+40)) return SAVE_CORRUPT; + memcpy(info->description,h+40,SAVE_DESCRIPTION);info->episode=CA_LE32(h+28);info->level=CA_LE32(h+32);info->difficulty=CA_LE32(h+36); + return SAVE_VALID; +} +/* Metadata inspection streams the integrity check, without deserializing or + changing the game. Full loads retain the bounded payload for staging. */ +static uint8_t *Read(unsigned slot,save_info *info,bool payload) +{ + char path[4096];memset(info,0,sizeof(*info));info->status=SAVE_UNAVAILABLE; + if(!Path(slot,path)) return NULL; + FILE *file=SaveFile_Open(path); + if(!file) { info->status=SaveFile_Missing(path)?SAVE_EMPTY:SAVE_UNAVAILABLE;return NULL; } + uint8_t h[SAVE_HEADER],buffer[4096],*data=NULL;long size; + info->status=SAVE_CORRUPT; + if(fseek(file,0,SEEK_END) || (size=ftell(file))<(long)SAVE_HEADER || + fseek(file,0,SEEK_SET) || fread(h,1,sizeof(h),file)!=sizeof(h)) goto done; + info->status=Header(h,(size_t)size,slot,info);if(info->status!=SAVE_VALID) goto done; + size_t left=CA_LE32(h+16);uint32_t expected=CA_LE32(h+24);Put32(h+24,0); + uint32_t crc=CRC(UINT32_MAX,h,sizeof(h)); + if(payload) { data=malloc((size_t)size);if(!data) { info->status=SAVE_UNAVAILABLE;goto done; }memcpy(data,h,sizeof(h)); } + size_t at=SAVE_HEADER; + while(left) { + size_t n=left>sizeof(buffer)?sizeof(buffer):left; + if(fread(buffer,1,n,file)!=n) { info->status=SAVE_CORRUPT;break; } + crc=CRC(crc,buffer,n);if(data) memcpy(data+at,buffer,n);at+=n;left-=n; + } + if(~crc!=expected || left) info->status=SAVE_CORRUPT; +done: + (void)fclose(file); + if(info->status!=SAVE_VALID) { free(data);data=NULL; } + return data; +} +void Save_ReadInfo(unsigned slot,save_info *info) { if(info) (void)Read(slot,info,false); } +bool Save_Write(unsigned slot,const char *description,bool overwrite) +{ + if(!GameCanSave()) return CA_Fail("Saving is unavailable during death, intermissions or victory"); + if(!Description(description)) return CA_Fail("Save description must contain 1-31 printable characters"); + char path[4096];if(!Path(slot,path)) return false; + snapshot *s=calloc(1,sizeof(*s));uint8_t *data=calloc(1,SAVE_HEADER+SAVE_LIMIT); + if(!s || !data) { free(s);free(data);return CA_Fail("Cannot allocate save buffer"); } + Capture(s);bool ok=Valid(s); + if(!ok) (void)CA_Fail("Current game cannot be represented by save version 1"); + codec c={data+SAVE_HEADER,0,SAVE_LIMIT,false,true};if(ok) Payload(&c,s); + if(ok) ok=c.ok; + if(ok) { + memcpy(data,"W3RSAVE",8);Put32(data+8,SAVE_VERSION);Put32(data+12,SAVE_HEADER);Put32(data+16,(uint32_t)c.pos);Put32(data+20,slot); + Put32(data+28,(unsigned)s->game.episode);Put32(data+32,(unsigned)s->game.mapon);Put32(data+36,(unsigned)s->game.difficulty); + memcpy(data+40,description,strlen(description));uint32_t ids[3];ok=Identity(ids); + if(ok) { + for(unsigned i=0;i<3;++i) Put32(data+72+i*4,ids[i]); + Put32(data+84,s->mode); + Put32(data+24,~CRC(UINT32_MAX,data,SAVE_HEADER+c.pos)); + ok=SaveFile_WriteAtomic(path,data,SAVE_HEADER+c.pos,overwrite); + if(!ok) (void)CA_Fail("Cannot replace save slot %u; previous save retained",slot+1); + } + } + free(data);free(s);return ok; +} +static bool Resources(snapshot *s) +{ + if(!CA_ReadMap((unsigned)(s->game.episode*10+s->game.mapon),&s->map)) return false; + if(!PM_Ready() && !PM_Startup()) return false; + uint8_t pixels[4096],mask[4096]; + for(unsigned i=0;icount;++i) if(s->used[i]) { + const statetype *state=Save_State(s->state[i+1]); + if(state->shapenum && !PM_DecodeSprite((unsigned)state->shapenum,pixels,mask)) return false; + } + for(unsigned i=0;istat_count;++i) if(s->stats[i].shapenum>=0 && !PM_DecodeSprite((unsigned)s->stats[i].shapenum,pixels,mask)) return false; + for(unsigned x=0;x<64;++x) for(unsigned y=0;y<64;++y) { + unsigned tile=s->walls[x][y];if(!tile || (tile&128)) continue;tile&=63; + if(tile && (tile*2-1>=PMSpriteStart || !PM_GetPage((tile-1)*2,NULL) || !PM_GetPage((tile-1)*2+1,NULL))) return false; + } + return true; +} +static objtype *Object(int ref) { return ref<0?NULL:&objlist[ref]; } +static void Apply(const snapshot *s,uint64_t ticks) +{ + gamestate=s->game;player=s->player;player.state=Save_State(s->state[0]);player.next=Object(s->next[0]); + memset(objlist,0,sizeof(objlist)); + for(unsigned i=0;icount;++i) if(s->used[i]) { + objlist[i]=s->actors[i];objlist[i].state=Save_State(s->state[i+1]);objlist[i].next=Object(s->next[i+1]); + } + objcount=s->count;statcount=s->stat_count;doornum=s->door_count;Save_SetActorAllocation(s->used); + memcpy(statobjlist,s->stats,sizeof(s->stats));memcpy(doorobjlist,s->doors,sizeof(s->doors)); + memcpy(tilemap,s->walls,sizeof(s->walls));memcpy(areaMap,s->areas,sizeof(s->areas)); + memcpy(staticblock,s->solid,sizeof(s->solid));memcpy(pushable,s->push,sizeof(s->push)); + for(unsigned x=0;x<64;++x) for(unsigned y=0;y<64;++y) actorat[x][y]=Object(s->at[x][y]); + memcpy(LevelRatios,s->ratios,sizeof(s->ratios));pwallstate=s->wall_state;pwallpos=s->wall_pos;pwallx=s->wall_x;pwally=s->wall_y;pwalldir=s->wall_dir; + thrustspeed=s->thrust;madenoise=s->noise;playstate=ex_playing;BuildTables();ConnectAreas(); + GameRestoreClock(ticks);Save_SetCombat(&s->controls);Save_SetAngleFraction(s->controls.anglefrac);US_InitRndT(s->rng);IN_ClearKeysDown(); + SD_SetDigitizedMode(s->mode!=0);SD_StopSound();SD_StartMusic(SD_LevelMusic((unsigned)gamestate.episode,(unsigned)gamestate.mapon));SD_FlushOutput(); + s_schabbdie2.tictime=s_giftdie2.tictime=s_fatdie2.tictime=s_hitlerdie2.tictime=s->mode?140:5; +} +bool Save_Load(unsigned slot,uint64_t ticks) +{ + save_info info;uint8_t *data=Read(slot,&info,true); + if(!data) return CA_Fail("Cannot load slot %u: %s",slot+1,info.status==SAVE_EMPTY?"empty":info.status==SAVE_UNSUPPORTED?"unsupported save version":info.status==SAVE_UNAVAILABLE?"storage unavailable":"corrupt save"); + snapshot *s=calloc(1,sizeof(*s));if(!s) { free(data);return CA_Fail("Cannot allocate load staging area"); } + codec c={data+SAVE_HEADER,0,CA_LE32(data+16),true,true};Payload(&c,s); + bool ok=c.ok && c.pos==c.size && Valid(s) && (unsigned)s->game.episode==info.episode && + (unsigned)s->game.mapon==info.level && (unsigned)s->game.difficulty==info.difficulty && s->mode==CA_LE32(data+84); + if(!ok) (void)CA_Fail("Invalid save state, coordinates or references"); + uint32_t ids[3]; + if(ok) { ok=Identity(ids);if(ok) for(unsigned i=0;i<3;++i) if(ids[i]!=CA_LE32(data+72+i*4)) { ok=CA_Fail("Save belongs to different original game resources");break; } } + if(ok) ok=Resources(s); + /* Last fallible operation. No active game fields change before this point. */ + if(ok) ok=CA_InstallMap(&s->map); + if(ok) Apply(s,ticks); + free(s);free(data);return ok; +} diff --git a/src/engine/WL_SAVE.h b/src/engine/WL_SAVE.h new file mode 100644 index 00000000..7d314605 --- /dev/null +++ b/src/engine/WL_SAVE.h @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef WL_SAVE_H +#define WL_SAVE_H +#include "WL_DEF.h" +#define SAVE_SLOTS 6 +#define SAVE_DESCRIPTION 32 +#define SAVE_VERSION 1U +typedef enum { SAVE_EMPTY,SAVE_VALID,SAVE_CORRUPT,SAVE_UNSUPPORTED,SAVE_UNAVAILABLE } save_status; +typedef struct { save_status status;char description[SAVE_DESCRIPTION];unsigned episode,level,difficulty,version; } save_info; +bool Save_SetDirectory(const char *directory); +const char *Save_Directory(void); +void Save_ReadInfo(unsigned slot,save_info *info); +bool Save_Write(unsigned slot,const char *description,bool overwrite); +bool Save_Load(unsigned slot,uint64_t ticks); +/* Internal snapshot boundaries. These structs are NEVER written as C bytes. */ +typedef struct { int facecount,anglefrac;bool attackheld,gotgatgun; } save_controls; +void Save_GetCombat(save_controls *controls); +void Save_SetCombat(const save_controls *controls); +int Save_GetAngleFraction(void); +void Save_SetAngleFraction(int fraction); +bool Save_ActorAllocated(unsigned slot); +void Save_SetActorAllocation(const bool used[MAXACTORS]); +bool GameCanSave(void); +bool GameRunning(void); +void GameRestoreClock(uint64_t ticks); +void GamePauseClock(uint64_t ticks); +bool GameDrawPaused(void); +/* Stable registry: append identifiers; changing existing entries requires a + format version bump. Zero means no state, never a process address. */ +unsigned Save_StateID(const statetype *state); +statetype *Save_State(unsigned id); +unsigned Save_StateCount(void); +#endif diff --git a/src/engine/WL_SAVE_MENU.c b/src/engine/WL_SAVE_MENU.c new file mode 100644 index 00000000..827fd994 --- /dev/null +++ b/src/engine/WL_SAVE_MENU.c @@ -0,0 +1,127 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_MENU.C DrawLoadSaveScreen/CP_SaveGame/CP_LoadGame, resumed through the + existing menu input queue. Six slots as requested; no separate UI toolkit. */ +#include "WL_MENU.h" +#include "WL_SAVE.h" +#include "ID_VH.h" +#include "ID_US_1.h" +#include "ID_IN.h" +#include "ID_CA.h" +#include "ID_SD.h" +#include +#include +static save_info entries[SAVE_SLOTS]; +static unsigned selected; +static bool saving; +unsigned SaveMenuSelected(void) { return selected; } +static enum { PICK_SLOT,OVERWRITE,EDIT_NAME,SLOT_ERROR,SLOT_WORK } phase; +bool SaveMenuEditing(void) { return phase==EDIT_NAME; } +static char name[SAVE_DESCRIPTION]; +static uint64_t work_at; +static bool work_done; +static bool DrawSlots(void) +{ + ClearMScreen();DrawStripes(10); + if(!VWB_DrawPic(60,0,saving?C_SAVEGAMEPIC:C_LOADGAMEPIC) || !VWB_DrawPic(112,184,C_MOUSELBACKPIC)) return false; + DrawWindow(75,50,175,6*13+10,BKGDCOLOR); + fontnumber=0; + for(unsigned i=0;istatus==SAVE_EMPTY?"- empty -":e->status==SAVE_UNSUPPORTED?"Unsupported version":e->status==SAVE_CORRUPT?"Corrupt save":e->status==SAVE_UNAVAILABLE?"Storage unavailable":e->description; + (void)snprintf(line,sizeof(line),"%s",phase==EDIT_NAME && i==selected?name:label); + int width,height; + while(*line) { + if(!VW_MeasurePropString(line,&width,&height)) return false; + if(width<=121) break; + line[strlen(line)-1]=0; + } + fontcolor=i==selected?HIGHLIGHT:TEXTCOLOR;PrintX=111;PrintY=56+(int)i*13; + if(!US_Print(line)) return false; + } + if(!VWB_DrawPic(85,53+(int)selected*13,C_CURSOR1PIC)) return false; + fontcolor=TEXTCOLOR;char details[80]; + if(entries[selected].status==SAVE_VALID) + (void)snprintf(details,sizeof(details),"Slot %u E%u / Floor %u / Skill %u",selected+1,entries[selected].episode+1,entries[selected].level+1,entries[selected].difficulty+1); + else (void)snprintf(details,sizeof(details),"Slot %u",selected+1); + PrintX=75;PrintY=147;if(!US_Print(details)) return false; + PrintX=75;PrintY=163; + return US_Print(phase==EDIT_NAME?"Enter saves; Esc cancels":"Enter selects; Esc returns"); +} +bool BeginSaveMenu(bool save) +{ + saving=save;phase=PICK_SLOT; + for(unsigned i=0;i=29) { message[at++]='\n';column=0; } + else { message[at++]=*p;++column; } + } + (void)strcpy(message+at,"\nPress a key to return.");return Message(message); +} +int HandleSaveMenu(uint64_t ticks) +{ + if(phase==SLOT_ERROR) { + if(IN_AnyPressed()) { phase=PICK_SLOT;IN_ClearKeysDown();if(!DrawSlots()) return -3; } + return 0; + } + if(phase==SLOT_WORK) { + if(ticks0) { if(!BeginName()) return -3; } + else if(answer<0) { phase=PICK_SLOT;if(!DrawSlots()) return -3; } + return 0; + } + if(phase==EDIT_NAME) { + if(IN_ConsumePress(sc_Escape)) { phase=PICK_SLOT;IN_ClearKeysDown();return DrawSlots()?0:-3; } + bool redraw=false; + if(IN_ConsumePress(0x0e) && *name) { name[strlen(name)-1]=0;redraw=true; } + char ch; + while((ch=IN_NextASCII())!=0) { + size_t n=strlen(name); + if(n>=SAVE_DESCRIPTION-1) continue; + name[n]=ch;name[n+1]=0;int width,height;fontnumber=0; + if(!VW_MeasurePropString(name,&width,&height)) return -3; + if(width>121) name[n]=0;else redraw=true; + } + if(IN_ConsumePress(sc_Enter)) { + if(!*name) (void)snprintf(name,sizeof(name),"E%d Floor %d",gamestate.episode+1,gamestate.mapon+1); + phase=SLOT_WORK;work_at=ticks+1;work_done=false;IN_ClearKeysDown(); + (void)SD_PlaySound(SHOOTSND,0,0);return DrawSaveActivity(true,false)?0:-3; + } + return !redraw || DrawSlots()?0:-3; + } + if(IN_ConsumePress(sc_Escape)) { (void)SD_PlaySound(ESCPRESSEDSND,0,0);return -1; } + int direction=MenuNavigation();bool up=direction<0,down=direction>0; + if(up || down) { selected=(selected+(up?SAVE_SLOTS-1U:1U))%SAVE_SLOTS;(void)SD_PlaySound(MOVEGUN1SND,0,0);if(!DrawSlots()) return -3; } + if(IN_ConsumePress(sc_Enter) || IN_ConsumePress(sc_Space)) { + if(saving) { + if(!GameCanSave()) return Error("No active game can be saved.")?0:-3; + if(entries[selected].status==SAVE_EMPTY) return BeginName()?0:-3; + phase=OVERWRITE;IN_ClearKeysDown();fontnumber=1; + return BeginConfirmation(entries[selected].status==SAVE_VALID?"There's already a game\nsaved at this position.\n Overwrite?":"Replace this invalid save?\nY / N",ticks)?0:-3; + } + if(entries[selected].status!=SAVE_VALID) return Error("This slot cannot be loaded.")?0:-3; + phase=SLOT_WORK;work_at=ticks+1;work_done=false;IN_ClearKeysDown(); + (void)SD_PlaySound(SHOOTSND,0,0);return DrawSaveActivity(false,false)?0:-3; + } + return 0; +} diff --git a/src/engine/WL_SAVE_STATES.inc b/src/engine/WL_SAVE_STATES.inc new file mode 100644 index 00000000..d15325bf --- /dev/null +++ b/src/engine/WL_SAVE_STATES.inc @@ -0,0 +1,305 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Version 1 state IDs. Append only; never reorder. ID 0 is NULL. */ +SAVE_STATE(s_grdstand) /* 1 */ +SAVE_STATE(s_grdpath1) /* 2 */ +SAVE_STATE(s_grdpath1s) /* 3 */ +SAVE_STATE(s_grdpath2) /* 4 */ +SAVE_STATE(s_grdpath3) /* 5 */ +SAVE_STATE(s_grdpath3s) /* 6 */ +SAVE_STATE(s_grdpath4) /* 7 */ +SAVE_STATE(s_grdpain) /* 8 */ +SAVE_STATE(s_grdpain1) /* 9 */ +SAVE_STATE(s_grdshoot1) /* 10 */ +SAVE_STATE(s_grdshoot2) /* 11 */ +SAVE_STATE(s_grdshoot3) /* 12 */ +SAVE_STATE(s_grdchase1) /* 13 */ +SAVE_STATE(s_grdchase1s) /* 14 */ +SAVE_STATE(s_grdchase2) /* 15 */ +SAVE_STATE(s_grdchase3) /* 16 */ +SAVE_STATE(s_grdchase3s) /* 17 */ +SAVE_STATE(s_grdchase4) /* 18 */ +SAVE_STATE(s_grddie1) /* 19 */ +SAVE_STATE(s_grddie2) /* 20 */ +SAVE_STATE(s_grddie3) /* 21 */ +SAVE_STATE(s_grddie4) /* 22 */ +SAVE_STATE(s_dogpath1) /* 23 */ +SAVE_STATE(s_dogpath1s) /* 24 */ +SAVE_STATE(s_dogpath2) /* 25 */ +SAVE_STATE(s_dogpath3) /* 26 */ +SAVE_STATE(s_dogpath3s) /* 27 */ +SAVE_STATE(s_dogpath4) /* 28 */ +SAVE_STATE(s_dogjump1) /* 29 */ +SAVE_STATE(s_dogjump2) /* 30 */ +SAVE_STATE(s_dogjump3) /* 31 */ +SAVE_STATE(s_dogjump4) /* 32 */ +SAVE_STATE(s_dogjump5) /* 33 */ +SAVE_STATE(s_dogchase1) /* 34 */ +SAVE_STATE(s_dogchase1s) /* 35 */ +SAVE_STATE(s_dogchase2) /* 36 */ +SAVE_STATE(s_dogchase3) /* 37 */ +SAVE_STATE(s_dogchase3s) /* 38 */ +SAVE_STATE(s_dogchase4) /* 39 */ +SAVE_STATE(s_dogdie1) /* 40 */ +SAVE_STATE(s_dogdie2) /* 41 */ +SAVE_STATE(s_dogdie3) /* 42 */ +SAVE_STATE(s_dogdead) /* 43 */ +SAVE_STATE(s_ofcstand) /* 44 */ +SAVE_STATE(s_ofcpath1) /* 45 */ +SAVE_STATE(s_ofcpath1s) /* 46 */ +SAVE_STATE(s_ofcpath2) /* 47 */ +SAVE_STATE(s_ofcpath3) /* 48 */ +SAVE_STATE(s_ofcpath3s) /* 49 */ +SAVE_STATE(s_ofcpath4) /* 50 */ +SAVE_STATE(s_ofcpain) /* 51 */ +SAVE_STATE(s_ofcpain1) /* 52 */ +SAVE_STATE(s_ofcshoot1) /* 53 */ +SAVE_STATE(s_ofcshoot2) /* 54 */ +SAVE_STATE(s_ofcshoot3) /* 55 */ +SAVE_STATE(s_ofcchase1) /* 56 */ +SAVE_STATE(s_ofcchase1s) /* 57 */ +SAVE_STATE(s_ofcchase2) /* 58 */ +SAVE_STATE(s_ofcchase3) /* 59 */ +SAVE_STATE(s_ofcchase3s) /* 60 */ +SAVE_STATE(s_ofcchase4) /* 61 */ +SAVE_STATE(s_ofcdie1) /* 62 */ +SAVE_STATE(s_ofcdie2) /* 63 */ +SAVE_STATE(s_ofcdie3) /* 64 */ +SAVE_STATE(s_ofcdie4) /* 65 */ +SAVE_STATE(s_ofcdie5) /* 66 */ +SAVE_STATE(s_mutstand) /* 67 */ +SAVE_STATE(s_mutpath1) /* 68 */ +SAVE_STATE(s_mutpath1s) /* 69 */ +SAVE_STATE(s_mutpath2) /* 70 */ +SAVE_STATE(s_mutpath3) /* 71 */ +SAVE_STATE(s_mutpath3s) /* 72 */ +SAVE_STATE(s_mutpath4) /* 73 */ +SAVE_STATE(s_mutpain) /* 74 */ +SAVE_STATE(s_mutpain1) /* 75 */ +SAVE_STATE(s_mutshoot1) /* 76 */ +SAVE_STATE(s_mutshoot2) /* 77 */ +SAVE_STATE(s_mutshoot3) /* 78 */ +SAVE_STATE(s_mutshoot4) /* 79 */ +SAVE_STATE(s_mutchase1) /* 80 */ +SAVE_STATE(s_mutchase1s) /* 81 */ +SAVE_STATE(s_mutchase2) /* 82 */ +SAVE_STATE(s_mutchase3) /* 83 */ +SAVE_STATE(s_mutchase3s) /* 84 */ +SAVE_STATE(s_mutchase4) /* 85 */ +SAVE_STATE(s_mutdie1) /* 86 */ +SAVE_STATE(s_mutdie2) /* 87 */ +SAVE_STATE(s_mutdie3) /* 88 */ +SAVE_STATE(s_mutdie4) /* 89 */ +SAVE_STATE(s_mutdie5) /* 90 */ +SAVE_STATE(s_ssstand) /* 91 */ +SAVE_STATE(s_sspath1) /* 92 */ +SAVE_STATE(s_sspath1s) /* 93 */ +SAVE_STATE(s_sspath2) /* 94 */ +SAVE_STATE(s_sspath3) /* 95 */ +SAVE_STATE(s_sspath3s) /* 96 */ +SAVE_STATE(s_sspath4) /* 97 */ +SAVE_STATE(s_sspain) /* 98 */ +SAVE_STATE(s_sspain1) /* 99 */ +SAVE_STATE(s_ssshoot1) /* 100 */ +SAVE_STATE(s_ssshoot2) /* 101 */ +SAVE_STATE(s_ssshoot3) /* 102 */ +SAVE_STATE(s_ssshoot4) /* 103 */ +SAVE_STATE(s_ssshoot5) /* 104 */ +SAVE_STATE(s_ssshoot6) /* 105 */ +SAVE_STATE(s_ssshoot7) /* 106 */ +SAVE_STATE(s_ssshoot8) /* 107 */ +SAVE_STATE(s_ssshoot9) /* 108 */ +SAVE_STATE(s_sschase1) /* 109 */ +SAVE_STATE(s_sschase1s) /* 110 */ +SAVE_STATE(s_sschase2) /* 111 */ +SAVE_STATE(s_sschase3) /* 112 */ +SAVE_STATE(s_sschase3s) /* 113 */ +SAVE_STATE(s_sschase4) /* 114 */ +SAVE_STATE(s_ssdie1) /* 115 */ +SAVE_STATE(s_ssdie2) /* 116 */ +SAVE_STATE(s_ssdie3) /* 117 */ +SAVE_STATE(s_ssdie4) /* 118 */ +SAVE_STATE(s_bossstand) /* 119 */ +SAVE_STATE(s_bosschase1) /* 120 */ +SAVE_STATE(s_bosschase1s) /* 121 */ +SAVE_STATE(s_bosschase2) /* 122 */ +SAVE_STATE(s_bosschase3) /* 123 */ +SAVE_STATE(s_bosschase3s) /* 124 */ +SAVE_STATE(s_bosschase4) /* 125 */ +SAVE_STATE(s_bossdie1) /* 126 */ +SAVE_STATE(s_bossdie2) /* 127 */ +SAVE_STATE(s_bossdie3) /* 128 */ +SAVE_STATE(s_bossdie4) /* 129 */ +SAVE_STATE(s_bossshoot1) /* 130 */ +SAVE_STATE(s_bossshoot2) /* 131 */ +SAVE_STATE(s_bossshoot3) /* 132 */ +SAVE_STATE(s_bossshoot4) /* 133 */ +SAVE_STATE(s_bossshoot5) /* 134 */ +SAVE_STATE(s_bossshoot6) /* 135 */ +SAVE_STATE(s_bossshoot7) /* 136 */ +SAVE_STATE(s_bossshoot8) /* 137 */ +SAVE_STATE(s_gretelstand) /* 138 */ +SAVE_STATE(s_gretelchase1) /* 139 */ +SAVE_STATE(s_gretelchase1s) /* 140 */ +SAVE_STATE(s_gretelchase2) /* 141 */ +SAVE_STATE(s_gretelchase3) /* 142 */ +SAVE_STATE(s_gretelchase3s) /* 143 */ +SAVE_STATE(s_gretelchase4) /* 144 */ +SAVE_STATE(s_greteldie1) /* 145 */ +SAVE_STATE(s_greteldie2) /* 146 */ +SAVE_STATE(s_greteldie3) /* 147 */ +SAVE_STATE(s_greteldie4) /* 148 */ +SAVE_STATE(s_gretelshoot1) /* 149 */ +SAVE_STATE(s_gretelshoot2) /* 150 */ +SAVE_STATE(s_gretelshoot3) /* 151 */ +SAVE_STATE(s_gretelshoot4) /* 152 */ +SAVE_STATE(s_gretelshoot5) /* 153 */ +SAVE_STATE(s_gretelshoot6) /* 154 */ +SAVE_STATE(s_gretelshoot7) /* 155 */ +SAVE_STATE(s_gretelshoot8) /* 156 */ +SAVE_STATE(s_blinkychase1) /* 157 */ +SAVE_STATE(s_blinkychase2) /* 158 */ +SAVE_STATE(s_clydechase1) /* 159 */ +SAVE_STATE(s_clydechase2) /* 160 */ +SAVE_STATE(s_pinkychase1) /* 161 */ +SAVE_STATE(s_pinkychase2) /* 162 */ +SAVE_STATE(s_inkychase1) /* 163 */ +SAVE_STATE(s_inkychase2) /* 164 */ +SAVE_STATE(s_rocket) /* 165 */ +SAVE_STATE(s_smoke1) /* 166 */ +SAVE_STATE(s_smoke2) /* 167 */ +SAVE_STATE(s_smoke3) /* 168 */ +SAVE_STATE(s_smoke4) /* 169 */ +SAVE_STATE(s_boom1) /* 170 */ +SAVE_STATE(s_boom2) /* 171 */ +SAVE_STATE(s_boom3) /* 172 */ +SAVE_STATE(s_schabbstand) /* 173 */ +SAVE_STATE(s_schabbchase1) /* 174 */ +SAVE_STATE(s_schabbchase1s) /* 175 */ +SAVE_STATE(s_schabbchase2) /* 176 */ +SAVE_STATE(s_schabbchase3) /* 177 */ +SAVE_STATE(s_schabbchase3s) /* 178 */ +SAVE_STATE(s_schabbchase4) /* 179 */ +SAVE_STATE(s_schabbdeathcam) /* 180 */ +SAVE_STATE(s_schabbdie1) /* 181 */ +SAVE_STATE(s_schabbdie2) /* 182 */ +SAVE_STATE(s_schabbdie3) /* 183 */ +SAVE_STATE(s_schabbdie4) /* 184 */ +SAVE_STATE(s_schabbdie5) /* 185 */ +SAVE_STATE(s_schabbdie6) /* 186 */ +SAVE_STATE(s_schabbshoot1) /* 187 */ +SAVE_STATE(s_schabbshoot2) /* 188 */ +SAVE_STATE(s_needle1) /* 189 */ +SAVE_STATE(s_needle2) /* 190 */ +SAVE_STATE(s_needle3) /* 191 */ +SAVE_STATE(s_needle4) /* 192 */ +SAVE_STATE(s_giftstand) /* 193 */ +SAVE_STATE(s_giftchase1) /* 194 */ +SAVE_STATE(s_giftchase1s) /* 195 */ +SAVE_STATE(s_giftchase2) /* 196 */ +SAVE_STATE(s_giftchase3) /* 197 */ +SAVE_STATE(s_giftchase3s) /* 198 */ +SAVE_STATE(s_giftchase4) /* 199 */ +SAVE_STATE(s_giftdeathcam) /* 200 */ +SAVE_STATE(s_giftdie1) /* 201 */ +SAVE_STATE(s_giftdie2) /* 202 */ +SAVE_STATE(s_giftdie3) /* 203 */ +SAVE_STATE(s_giftdie4) /* 204 */ +SAVE_STATE(s_giftdie5) /* 205 */ +SAVE_STATE(s_giftdie6) /* 206 */ +SAVE_STATE(s_giftshoot1) /* 207 */ +SAVE_STATE(s_giftshoot2) /* 208 */ +SAVE_STATE(s_fatstand) /* 209 */ +SAVE_STATE(s_fatchase1) /* 210 */ +SAVE_STATE(s_fatchase1s) /* 211 */ +SAVE_STATE(s_fatchase2) /* 212 */ +SAVE_STATE(s_fatchase3) /* 213 */ +SAVE_STATE(s_fatchase3s) /* 214 */ +SAVE_STATE(s_fatchase4) /* 215 */ +SAVE_STATE(s_fatdeathcam) /* 216 */ +SAVE_STATE(s_fatdie1) /* 217 */ +SAVE_STATE(s_fatdie2) /* 218 */ +SAVE_STATE(s_fatdie3) /* 219 */ +SAVE_STATE(s_fatdie4) /* 220 */ +SAVE_STATE(s_fatdie5) /* 221 */ +SAVE_STATE(s_fatdie6) /* 222 */ +SAVE_STATE(s_fatshoot1) /* 223 */ +SAVE_STATE(s_fatshoot2) /* 224 */ +SAVE_STATE(s_fatshoot3) /* 225 */ +SAVE_STATE(s_fatshoot4) /* 226 */ +SAVE_STATE(s_fatshoot5) /* 227 */ +SAVE_STATE(s_fatshoot6) /* 228 */ +SAVE_STATE(s_fakestand) /* 229 */ +SAVE_STATE(s_fakechase1) /* 230 */ +SAVE_STATE(s_fakechase1s) /* 231 */ +SAVE_STATE(s_fakechase2) /* 232 */ +SAVE_STATE(s_fakechase3) /* 233 */ +SAVE_STATE(s_fakechase3s) /* 234 */ +SAVE_STATE(s_fakechase4) /* 235 */ +SAVE_STATE(s_fakedie1) /* 236 */ +SAVE_STATE(s_fakedie2) /* 237 */ +SAVE_STATE(s_fakedie3) /* 238 */ +SAVE_STATE(s_fakedie4) /* 239 */ +SAVE_STATE(s_fakedie5) /* 240 */ +SAVE_STATE(s_fakedie6) /* 241 */ +SAVE_STATE(s_fakeshoot1) /* 242 */ +SAVE_STATE(s_fakeshoot2) /* 243 */ +SAVE_STATE(s_fakeshoot3) /* 244 */ +SAVE_STATE(s_fakeshoot4) /* 245 */ +SAVE_STATE(s_fakeshoot5) /* 246 */ +SAVE_STATE(s_fakeshoot6) /* 247 */ +SAVE_STATE(s_fakeshoot7) /* 248 */ +SAVE_STATE(s_fakeshoot8) /* 249 */ +SAVE_STATE(s_fakeshoot9) /* 250 */ +SAVE_STATE(s_fire1) /* 251 */ +SAVE_STATE(s_fire2) /* 252 */ +SAVE_STATE(s_mechastand) /* 253 */ +SAVE_STATE(s_mechachase1) /* 254 */ +SAVE_STATE(s_mechachase1s) /* 255 */ +SAVE_STATE(s_mechachase2) /* 256 */ +SAVE_STATE(s_mechachase3) /* 257 */ +SAVE_STATE(s_mechachase3s) /* 258 */ +SAVE_STATE(s_mechachase4) /* 259 */ +SAVE_STATE(s_mechadie1) /* 260 */ +SAVE_STATE(s_mechadie2) /* 261 */ +SAVE_STATE(s_mechadie3) /* 262 */ +SAVE_STATE(s_mechadie4) /* 263 */ +SAVE_STATE(s_mechashoot1) /* 264 */ +SAVE_STATE(s_mechashoot2) /* 265 */ +SAVE_STATE(s_mechashoot3) /* 266 */ +SAVE_STATE(s_mechashoot4) /* 267 */ +SAVE_STATE(s_mechashoot5) /* 268 */ +SAVE_STATE(s_mechashoot6) /* 269 */ +SAVE_STATE(s_hitlerchase1) /* 270 */ +SAVE_STATE(s_hitlerchase1s) /* 271 */ +SAVE_STATE(s_hitlerchase2) /* 272 */ +SAVE_STATE(s_hitlerchase3) /* 273 */ +SAVE_STATE(s_hitlerchase3s) /* 274 */ +SAVE_STATE(s_hitlerchase4) /* 275 */ +SAVE_STATE(s_hitlerdeathcam) /* 276 */ +SAVE_STATE(s_hitlerdie1) /* 277 */ +SAVE_STATE(s_hitlerdie2) /* 278 */ +SAVE_STATE(s_hitlerdie3) /* 279 */ +SAVE_STATE(s_hitlerdie4) /* 280 */ +SAVE_STATE(s_hitlerdie5) /* 281 */ +SAVE_STATE(s_hitlerdie6) /* 282 */ +SAVE_STATE(s_hitlerdie7) /* 283 */ +SAVE_STATE(s_hitlerdie8) /* 284 */ +SAVE_STATE(s_hitlerdie9) /* 285 */ +SAVE_STATE(s_hitlerdie10) /* 286 */ +SAVE_STATE(s_hitlershoot1) /* 287 */ +SAVE_STATE(s_hitlershoot2) /* 288 */ +SAVE_STATE(s_hitlershoot3) /* 289 */ +SAVE_STATE(s_hitlershoot4) /* 290 */ +SAVE_STATE(s_hitlershoot5) /* 291 */ +SAVE_STATE(s_hitlershoot6) /* 292 */ +SAVE_STATE(s_deathcam) /* 293 */ +SAVE_STATE(s_bjrun1) /* 294 */ +SAVE_STATE(s_bjrun1s) /* 295 */ +SAVE_STATE(s_bjrun2) /* 296 */ +SAVE_STATE(s_bjrun3) /* 297 */ +SAVE_STATE(s_bjrun3s) /* 298 */ +SAVE_STATE(s_bjrun4) /* 299 */ +SAVE_STATE(s_bjjump1) /* 300 */ +SAVE_STATE(s_bjjump2) /* 301 */ +SAVE_STATE(s_bjjump3) /* 302 */ +SAVE_STATE(s_bjjump4) /* 303 */ diff --git a/src/engine/WL_SCALE.c b/src/engine/WL_SCALE.c new file mode 100644 index 00000000..224fee5c --- /dev/null +++ b/src/engine/WL_SCALE.c @@ -0,0 +1,69 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* WL_SCALE.C BuildCompScale and WL_DRAW.C ScalePost without generated x86. + Emit the original source-pixel runs, including scaler-directory quantization. */ +#include "WL_DEF.h" +#include "ID_VL.h" +#include "ID_PM.h" +#include "ID_FILE.h" +void ScalePost(unsigned x,unsigned width,unsigned height,const w3r_byte *source) +{ + unsigned scale=height/8; + unsigned maxscale=(unsigned)VIEWWIDTH*3/4-1; + if (scale>maxscale) scale=maxscale; + if (!scale) scale=1; + unsigned stepbytwo=VIEWHEIGHT/2; + if (scale>=stepbytwo) scale=stepbytwo+(scale-stepbytwo)/3*3; + int pixels=(int)scale*2,top=(VIEWHEIGHT-pixels)/2; + int32_t step=pixels*65536/64,fix=0; + for (unsigned row=0;row<64;++row) { + int start=fix/65536+top; fix+=step; int end=fix/65536+top; + if (start<0) start=0; + if (end>VIEWHEIGHT) end=VIEWHEIGHT; + for (int y=start;y(unsigned)VIEWWIDTH*3/4-1) return true; + if (scale>=VIEWHEIGHT/2) scale=VIEWHEIGHT/2+(scale-VIEWHEIGHT/2)/3*3; + w3r_byte pixels[4096],opaque[4096]; + if (!PM_DecodeSprite(sprite,pixels,opaque)) return false; + const w3r_byte *page=PM_GetPage(PMSpriteStart+sprite,NULL); + int first=(int)CA_LE16(page),last=(int)CA_LE16(page+2); + int size=(int)scale*2,top=(VIEWHEIGHT-size)/2; + /* Original ScaleShape anchors both halves independently at xcenter. + In particular, a shape wholly right of column 31 starts AT center; + treating the decoded bitmap as a centered square shifts knife frames. */ + for (int half=0;half<2;++half) { + int cursor=center; + int start=half ? (first<31 ? 32 : first) : 31; + int stop=half ? last : first; + int step=half ? 1 : -1; + for (int sx=start;half ? sx<=stop : sx>=stop;sx+=step) { + int width=(sx+1)*size/64-sx*size/64; + if (!half) cursor-=width; + int x0=cursor,x1=cursor+width; + if (half) cursor+=width; + if (x0<0) x0=0; + if (x1>VIEWWIDTH) x1=VIEWWIDTH; + for (int sy=0;sy<64;++sy) { + if (!opaque[sy*64+sx]) continue; + int y0=top+sy*size/64,y1=top+(sy+1)*size/64; + if (y0<0) y0=0; + if (y1>VIEWHEIGHT) y1=VIEWHEIGHT; + for (int x=x0;x=height) continue; + for (int y=y0;y +#include +#define tics SimulationTics() +#define MAPSIZE 64 +#define MAPSPOT(x,y,p) (CA_Map()->planes[(p)][(y)*64+(x)]) +extern statetype s_grdstand; +extern statetype s_grdpath1; +extern statetype s_grdpath1s; +extern statetype s_grdpath2; +extern statetype s_grdpath3; +extern statetype s_grdpath3s; +extern statetype s_grdpath4; +extern statetype s_grdpain; +extern statetype s_grdpain1; +extern statetype s_grdshoot1; +extern statetype s_grdshoot2; +extern statetype s_grdshoot3; +extern statetype s_grdchase1; +extern statetype s_grdchase1s; +extern statetype s_grdchase2; +extern statetype s_grdchase3; +extern statetype s_grdchase3s; +extern statetype s_grdchase4; +extern statetype s_grddie1; +extern statetype s_grddie2; +extern statetype s_grddie3; +extern statetype s_grddie4; +extern statetype s_dogpath1; +extern statetype s_dogpath1s; +extern statetype s_dogpath2; +extern statetype s_dogpath3; +extern statetype s_dogpath3s; +extern statetype s_dogpath4; +extern statetype s_dogjump1; +extern statetype s_dogjump2; +extern statetype s_dogjump3; +extern statetype s_dogjump4; +extern statetype s_dogjump5; +extern statetype s_dogchase1; +extern statetype s_dogchase1s; +extern statetype s_dogchase2; +extern statetype s_dogchase3; +extern statetype s_dogchase3s; +extern statetype s_dogchase4; +extern statetype s_dogdie1; +extern statetype s_dogdie2; +extern statetype s_dogdie3; +extern statetype s_dogdead; +extern statetype s_ofcstand; +extern statetype s_ofcpath1; +extern statetype s_ofcpath1s; +extern statetype s_ofcpath2; +extern statetype s_ofcpath3; +extern statetype s_ofcpath3s; +extern statetype s_ofcpath4; +extern statetype s_ofcpain; +extern statetype s_ofcpain1; +extern statetype s_ofcshoot1; +extern statetype s_ofcshoot2; +extern statetype s_ofcshoot3; +extern statetype s_ofcchase1; +extern statetype s_ofcchase1s; +extern statetype s_ofcchase2; +extern statetype s_ofcchase3; +extern statetype s_ofcchase3s; +extern statetype s_ofcchase4; +extern statetype s_ofcdie1; +extern statetype s_ofcdie2; +extern statetype s_ofcdie3; +extern statetype s_ofcdie4; +extern statetype s_ofcdie5; +extern statetype s_mutstand; +extern statetype s_mutpath1; +extern statetype s_mutpath1s; +extern statetype s_mutpath2; +extern statetype s_mutpath3; +extern statetype s_mutpath3s; +extern statetype s_mutpath4; +extern statetype s_mutpain; +extern statetype s_mutpain1; +extern statetype s_mutshoot1; +extern statetype s_mutshoot2; +extern statetype s_mutshoot3; +extern statetype s_mutshoot4; +extern statetype s_mutchase1; +extern statetype s_mutchase1s; +extern statetype s_mutchase2; +extern statetype s_mutchase3; +extern statetype s_mutchase3s; +extern statetype s_mutchase4; +extern statetype s_mutdie1; +extern statetype s_mutdie2; +extern statetype s_mutdie3; +extern statetype s_mutdie4; +extern statetype s_mutdie5; +extern statetype s_ssstand; +extern statetype s_sspath1; +extern statetype s_sspath1s; +extern statetype s_sspath2; +extern statetype s_sspath3; +extern statetype s_sspath3s; +extern statetype s_sspath4; +extern statetype s_sspain; +extern statetype s_sspain1; +extern statetype s_ssshoot1; +extern statetype s_ssshoot2; +extern statetype s_ssshoot3; +extern statetype s_ssshoot4; +extern statetype s_ssshoot5; +extern statetype s_ssshoot6; +extern statetype s_ssshoot7; +extern statetype s_ssshoot8; +extern statetype s_ssshoot9; +extern statetype s_sschase1; +extern statetype s_sschase1s; +extern statetype s_sschase2; +extern statetype s_sschase3; +extern statetype s_sschase3s; +extern statetype s_sschase4; +extern statetype s_ssdie1; +extern statetype s_ssdie2; +extern statetype s_ssdie3; +extern statetype s_ssdie4; +statetype s_grdstand = {true,SPR_GRD_S_1,0,T_Stand,NULL,&s_grdstand}; +statetype s_grdpath1 = {true,SPR_GRD_W1_1,20,T_Path,NULL,&s_grdpath1s}; +statetype s_grdpath1s = {true,SPR_GRD_W1_1,5,NULL,NULL,&s_grdpath2}; +statetype s_grdpath2 = {true,SPR_GRD_W2_1,15,T_Path,NULL,&s_grdpath3}; +statetype s_grdpath3 = {true,SPR_GRD_W3_1,20,T_Path,NULL,&s_grdpath3s}; +statetype s_grdpath3s = {true,SPR_GRD_W3_1,5,NULL,NULL,&s_grdpath4}; +statetype s_grdpath4 = {true,SPR_GRD_W4_1,15,T_Path,NULL,&s_grdpath1}; +statetype s_grdpain = {2,SPR_GRD_PAIN_1,10,NULL,NULL,&s_grdchase1}; +statetype s_grdpain1 = {2,SPR_GRD_PAIN_2,10,NULL,NULL,&s_grdchase1}; +statetype s_grdshoot1 = {false,SPR_GRD_SHOOT1,20,NULL,NULL,&s_grdshoot2}; +statetype s_grdshoot2 = {false,SPR_GRD_SHOOT2,20,NULL,T_Shoot,&s_grdshoot3}; +statetype s_grdshoot3 = {false,SPR_GRD_SHOOT3,20,NULL,NULL,&s_grdchase1}; +statetype s_grdchase1 = {true,SPR_GRD_W1_1,10,T_Chase,NULL,&s_grdchase1s}; +statetype s_grdchase1s = {true,SPR_GRD_W1_1,3,NULL,NULL,&s_grdchase2}; +statetype s_grdchase2 = {true,SPR_GRD_W2_1,8,T_Chase,NULL,&s_grdchase3}; +statetype s_grdchase3 = {true,SPR_GRD_W3_1,10,T_Chase,NULL,&s_grdchase3s}; +statetype s_grdchase3s = {true,SPR_GRD_W3_1,3,NULL,NULL,&s_grdchase4}; +statetype s_grdchase4 = {true,SPR_GRD_W4_1,8,T_Chase,NULL,&s_grdchase1}; +statetype s_grddie1 = {false,SPR_GRD_DIE_1,15,NULL,A_DeathScream,&s_grddie2}; +statetype s_grddie2 = {false,SPR_GRD_DIE_2,15,NULL,NULL,&s_grddie3}; +statetype s_grddie3 = {false,SPR_GRD_DIE_3,15,NULL,NULL,&s_grddie4}; +statetype s_grddie4 = {false,SPR_GRD_DEAD,0,NULL,NULL,&s_grddie4}; +statetype s_dogpath1 = {true,SPR_DOG_W1_1,20,T_Path,NULL,&s_dogpath1s}; +statetype s_dogpath1s = {true,SPR_DOG_W1_1,5,NULL,NULL,&s_dogpath2}; +statetype s_dogpath2 = {true,SPR_DOG_W2_1,15,T_Path,NULL,&s_dogpath3}; +statetype s_dogpath3 = {true,SPR_DOG_W3_1,20,T_Path,NULL,&s_dogpath3s}; +statetype s_dogpath3s = {true,SPR_DOG_W3_1,5,NULL,NULL,&s_dogpath4}; +statetype s_dogpath4 = {true,SPR_DOG_W4_1,15,T_Path,NULL,&s_dogpath1}; +statetype s_dogjump1 = {false,SPR_DOG_JUMP1,10,NULL,NULL,&s_dogjump2}; +statetype s_dogjump2 = {false,SPR_DOG_JUMP2,10,NULL,T_Bite,&s_dogjump3}; +statetype s_dogjump3 = {false,SPR_DOG_JUMP3,10,NULL,NULL,&s_dogjump4}; +statetype s_dogjump4 = {false,SPR_DOG_JUMP1,10,NULL,NULL,&s_dogjump5}; +statetype s_dogjump5 = {false,SPR_DOG_W1_1,10,NULL,NULL,&s_dogchase1}; +statetype s_dogchase1 = {true,SPR_DOG_W1_1,10,T_DogChase,NULL,&s_dogchase1s}; +statetype s_dogchase1s = {true,SPR_DOG_W1_1,3,NULL,NULL,&s_dogchase2}; +statetype s_dogchase2 = {true,SPR_DOG_W2_1,8,T_DogChase,NULL,&s_dogchase3}; +statetype s_dogchase3 = {true,SPR_DOG_W3_1,10,T_DogChase,NULL,&s_dogchase3s}; +statetype s_dogchase3s = {true,SPR_DOG_W3_1,3,NULL,NULL,&s_dogchase4}; +statetype s_dogchase4 = {true,SPR_DOG_W4_1,8,T_DogChase,NULL,&s_dogchase1}; +statetype s_dogdie1 = {false,SPR_DOG_DIE_1,15,NULL,A_DeathScream,&s_dogdie2}; +statetype s_dogdie2 = {false,SPR_DOG_DIE_2,15,NULL,NULL,&s_dogdie3}; +statetype s_dogdie3 = {false,SPR_DOG_DIE_3,15,NULL,NULL,&s_dogdead}; +statetype s_dogdead = {false,SPR_DOG_DEAD,15,NULL,NULL,&s_dogdead}; +statetype s_ofcstand = {true,SPR_OFC_S_1,0,T_Stand,NULL,&s_ofcstand}; +statetype s_ofcpath1 = {true,SPR_OFC_W1_1,20,T_Path,NULL,&s_ofcpath1s}; +statetype s_ofcpath1s = {true,SPR_OFC_W1_1,5,NULL,NULL,&s_ofcpath2}; +statetype s_ofcpath2 = {true,SPR_OFC_W2_1,15,T_Path,NULL,&s_ofcpath3}; +statetype s_ofcpath3 = {true,SPR_OFC_W3_1,20,T_Path,NULL,&s_ofcpath3s}; +statetype s_ofcpath3s = {true,SPR_OFC_W3_1,5,NULL,NULL,&s_ofcpath4}; +statetype s_ofcpath4 = {true,SPR_OFC_W4_1,15,T_Path,NULL,&s_ofcpath1}; +statetype s_ofcpain = {2,SPR_OFC_PAIN_1,10,NULL,NULL,&s_ofcchase1}; +statetype s_ofcpain1 = {2,SPR_OFC_PAIN_2,10,NULL,NULL,&s_ofcchase1}; +statetype s_ofcshoot1 = {false,SPR_OFC_SHOOT1,6,NULL,NULL,&s_ofcshoot2}; +statetype s_ofcshoot2 = {false,SPR_OFC_SHOOT2,20,NULL,T_Shoot,&s_ofcshoot3}; +statetype s_ofcshoot3 = {false,SPR_OFC_SHOOT3,10,NULL,NULL,&s_ofcchase1}; +statetype s_ofcchase1 = {true,SPR_OFC_W1_1,10,T_Chase,NULL,&s_ofcchase1s}; +statetype s_ofcchase1s = {true,SPR_OFC_W1_1,3,NULL,NULL,&s_ofcchase2}; +statetype s_ofcchase2 = {true,SPR_OFC_W2_1,8,T_Chase,NULL,&s_ofcchase3}; +statetype s_ofcchase3 = {true,SPR_OFC_W3_1,10,T_Chase,NULL,&s_ofcchase3s}; +statetype s_ofcchase3s = {true,SPR_OFC_W3_1,3,NULL,NULL,&s_ofcchase4}; +statetype s_ofcchase4 = {true,SPR_OFC_W4_1,8,T_Chase,NULL,&s_ofcchase1}; +statetype s_ofcdie1 = {false,SPR_OFC_DIE_1,11,NULL,A_DeathScream,&s_ofcdie2}; +statetype s_ofcdie2 = {false,SPR_OFC_DIE_2,11,NULL,NULL,&s_ofcdie3}; +statetype s_ofcdie3 = {false,SPR_OFC_DIE_3,11,NULL,NULL,&s_ofcdie4}; +statetype s_ofcdie4 = {false,SPR_OFC_DIE_4,11,NULL,NULL,&s_ofcdie5}; +statetype s_ofcdie5 = {false,SPR_OFC_DEAD,0,NULL,NULL,&s_ofcdie5}; +statetype s_mutstand = {true,SPR_MUT_S_1,0,T_Stand,NULL,&s_mutstand}; +statetype s_mutpath1 = {true,SPR_MUT_W1_1,20,T_Path,NULL,&s_mutpath1s}; +statetype s_mutpath1s = {true,SPR_MUT_W1_1,5,NULL,NULL,&s_mutpath2}; +statetype s_mutpath2 = {true,SPR_MUT_W2_1,15,T_Path,NULL,&s_mutpath3}; +statetype s_mutpath3 = {true,SPR_MUT_W3_1,20,T_Path,NULL,&s_mutpath3s}; +statetype s_mutpath3s = {true,SPR_MUT_W3_1,5,NULL,NULL,&s_mutpath4}; +statetype s_mutpath4 = {true,SPR_MUT_W4_1,15,T_Path,NULL,&s_mutpath1}; +statetype s_mutpain = {2,SPR_MUT_PAIN_1,10,NULL,NULL,&s_mutchase1}; +statetype s_mutpain1 = {2,SPR_MUT_PAIN_2,10,NULL,NULL,&s_mutchase1}; +statetype s_mutshoot1 = {false,SPR_MUT_SHOOT1,6,NULL,T_Shoot,&s_mutshoot2}; +statetype s_mutshoot2 = {false,SPR_MUT_SHOOT2,20,NULL,NULL,&s_mutshoot3}; +statetype s_mutshoot3 = {false,SPR_MUT_SHOOT3,10,NULL,T_Shoot,&s_mutshoot4}; +statetype s_mutshoot4 = {false,SPR_MUT_SHOOT4,20,NULL,NULL,&s_mutchase1}; +statetype s_mutchase1 = {true,SPR_MUT_W1_1,10,T_Chase,NULL,&s_mutchase1s}; +statetype s_mutchase1s = {true,SPR_MUT_W1_1,3,NULL,NULL,&s_mutchase2}; +statetype s_mutchase2 = {true,SPR_MUT_W2_1,8,T_Chase,NULL,&s_mutchase3}; +statetype s_mutchase3 = {true,SPR_MUT_W3_1,10,T_Chase,NULL,&s_mutchase3s}; +statetype s_mutchase3s = {true,SPR_MUT_W3_1,3,NULL,NULL,&s_mutchase4}; +statetype s_mutchase4 = {true,SPR_MUT_W4_1,8,T_Chase,NULL,&s_mutchase1}; +statetype s_mutdie1 = {false,SPR_MUT_DIE_1,7,NULL,A_DeathScream,&s_mutdie2}; +statetype s_mutdie2 = {false,SPR_MUT_DIE_2,7,NULL,NULL,&s_mutdie3}; +statetype s_mutdie3 = {false,SPR_MUT_DIE_3,7,NULL,NULL,&s_mutdie4}; +statetype s_mutdie4 = {false,SPR_MUT_DIE_4,7,NULL,NULL,&s_mutdie5}; +statetype s_mutdie5 = {false,SPR_MUT_DEAD,0,NULL,NULL,&s_mutdie5}; +statetype s_ssstand = {true,SPR_SS_S_1,0,T_Stand,NULL,&s_ssstand}; +statetype s_sspath1 = {true,SPR_SS_W1_1,20,T_Path,NULL,&s_sspath1s}; +statetype s_sspath1s = {true,SPR_SS_W1_1,5,NULL,NULL,&s_sspath2}; +statetype s_sspath2 = {true,SPR_SS_W2_1,15,T_Path,NULL,&s_sspath3}; +statetype s_sspath3 = {true,SPR_SS_W3_1,20,T_Path,NULL,&s_sspath3s}; +statetype s_sspath3s = {true,SPR_SS_W3_1,5,NULL,NULL,&s_sspath4}; +statetype s_sspath4 = {true,SPR_SS_W4_1,15,T_Path,NULL,&s_sspath1}; +statetype s_sspain = {2,SPR_SS_PAIN_1,10,NULL,NULL,&s_sschase1}; +statetype s_sspain1 = {2,SPR_SS_PAIN_2,10,NULL,NULL,&s_sschase1}; +statetype s_ssshoot1 = {false,SPR_SS_SHOOT1,20,NULL,NULL,&s_ssshoot2}; +statetype s_ssshoot2 = {false,SPR_SS_SHOOT2,20,NULL,T_Shoot,&s_ssshoot3}; +statetype s_ssshoot3 = {false,SPR_SS_SHOOT3,10,NULL,NULL,&s_ssshoot4}; +statetype s_ssshoot4 = {false,SPR_SS_SHOOT2,10,NULL,T_Shoot,&s_ssshoot5}; +statetype s_ssshoot5 = {false,SPR_SS_SHOOT3,10,NULL,NULL,&s_ssshoot6}; +statetype s_ssshoot6 = {false,SPR_SS_SHOOT2,10,NULL,T_Shoot,&s_ssshoot7}; +statetype s_ssshoot7 = {false,SPR_SS_SHOOT3,10,NULL,NULL,&s_ssshoot8}; +statetype s_ssshoot8 = {false,SPR_SS_SHOOT2,10,NULL,T_Shoot,&s_ssshoot9}; +statetype s_ssshoot9 = {false,SPR_SS_SHOOT3,10,NULL,NULL,&s_sschase1}; +statetype s_sschase1 = {true,SPR_SS_W1_1,10,T_Chase,NULL,&s_sschase1s}; +statetype s_sschase1s = {true,SPR_SS_W1_1,3,NULL,NULL,&s_sschase2}; +statetype s_sschase2 = {true,SPR_SS_W2_1,8,T_Chase,NULL,&s_sschase3}; +statetype s_sschase3 = {true,SPR_SS_W3_1,10,T_Chase,NULL,&s_sschase3s}; +statetype s_sschase3s = {true,SPR_SS_W3_1,3,NULL,NULL,&s_sschase4}; +statetype s_sschase4 = {true,SPR_SS_W4_1,8,T_Chase,NULL,&s_sschase1}; +statetype s_ssdie1 = {false,SPR_SS_DIE_1,15,NULL,A_DeathScream,&s_ssdie2}; +statetype s_ssdie2 = {false,SPR_SS_DIE_2,15,NULL,NULL,&s_ssdie3}; +statetype s_ssdie3 = {false,SPR_SS_DIE_3,15,NULL,NULL,&s_ssdie4}; +statetype s_ssdie4 = {false,SPR_SS_DEAD,0,NULL,NULL,&s_ssdie4}; +/* Hans, Gretel and ghost states from id Software WL_ACT2.C. + Original source/licensing: WOLFSRC/ and docs/LICENSING.md. */ +extern statetype s_bossstand; +extern statetype s_bosschase1; +extern statetype s_bosschase1s; +extern statetype s_bosschase2; +extern statetype s_bosschase3; +extern statetype s_bosschase3s; +extern statetype s_bosschase4; +extern statetype s_bossdie1; +extern statetype s_bossdie2; +extern statetype s_bossdie3; +extern statetype s_bossdie4; +extern statetype s_bossshoot1; +extern statetype s_bossshoot2; +extern statetype s_bossshoot3; +extern statetype s_bossshoot4; +extern statetype s_bossshoot5; +extern statetype s_bossshoot6; +extern statetype s_bossshoot7; +extern statetype s_bossshoot8; +extern statetype s_gretelstand; +extern statetype s_gretelchase1; +extern statetype s_gretelchase1s; +extern statetype s_gretelchase2; +extern statetype s_gretelchase3; +extern statetype s_gretelchase3s; +extern statetype s_gretelchase4; +extern statetype s_greteldie1; +extern statetype s_greteldie2; +extern statetype s_greteldie3; +extern statetype s_greteldie4; +extern statetype s_gretelshoot1; +extern statetype s_gretelshoot2; +extern statetype s_gretelshoot3; +extern statetype s_gretelshoot4; +extern statetype s_gretelshoot5; +extern statetype s_gretelshoot6; +extern statetype s_gretelshoot7; +extern statetype s_gretelshoot8; +extern statetype s_blinkychase1; +extern statetype s_blinkychase2; +extern statetype s_clydechase1; +extern statetype s_clydechase2; +extern statetype s_pinkychase1; +extern statetype s_pinkychase2; +extern statetype s_inkychase1; +extern statetype s_inkychase2; + +statetype s_bossstand = {false,SPR_BOSS_W1,0,T_Stand,NULL,&s_bossstand}; +statetype s_bosschase1 = {false,SPR_BOSS_W1,10,T_Chase,NULL,&s_bosschase1s}; +statetype s_bosschase1s = {false,SPR_BOSS_W1,3,NULL,NULL,&s_bosschase2}; +statetype s_bosschase2 = {false,SPR_BOSS_W2,8,T_Chase,NULL,&s_bosschase3}; +statetype s_bosschase3 = {false,SPR_BOSS_W3,10,T_Chase,NULL,&s_bosschase3s}; +statetype s_bosschase3s = {false,SPR_BOSS_W3,3,NULL,NULL,&s_bosschase4}; +statetype s_bosschase4 = {false,SPR_BOSS_W4,8,T_Chase,NULL,&s_bosschase1}; +statetype s_bossdie1 = {false,SPR_BOSS_DIE1,15,NULL,A_DeathScream,&s_bossdie2}; +statetype s_bossdie2 = {false,SPR_BOSS_DIE2,15,NULL,NULL,&s_bossdie3}; +statetype s_bossdie3 = {false,SPR_BOSS_DIE3,15,NULL,NULL,&s_bossdie4}; +statetype s_bossdie4 = {false,SPR_BOSS_DEAD,0,NULL,NULL,&s_bossdie4}; +statetype s_bossshoot1 = {false,SPR_BOSS_SHOOT1,30,NULL,NULL,&s_bossshoot2}; +statetype s_bossshoot2 = {false,SPR_BOSS_SHOOT2,10,NULL,T_Shoot,&s_bossshoot3}; +statetype s_bossshoot3 = {false,SPR_BOSS_SHOOT3,10,NULL,T_Shoot,&s_bossshoot4}; +statetype s_bossshoot4 = {false,SPR_BOSS_SHOOT2,10,NULL,T_Shoot,&s_bossshoot5}; +statetype s_bossshoot5 = {false,SPR_BOSS_SHOOT3,10,NULL,T_Shoot,&s_bossshoot6}; +statetype s_bossshoot6 = {false,SPR_BOSS_SHOOT2,10,NULL,T_Shoot,&s_bossshoot7}; +statetype s_bossshoot7 = {false,SPR_BOSS_SHOOT3,10,NULL,T_Shoot,&s_bossshoot8}; +statetype s_bossshoot8 = {false,SPR_BOSS_SHOOT1,10,NULL,NULL,&s_bosschase1}; +statetype s_gretelstand = {false,SPR_GRETEL_W1,0,T_Stand,NULL,&s_gretelstand}; +statetype s_gretelchase1 = {false,SPR_GRETEL_W1,10,T_Chase,NULL,&s_gretelchase1s}; +statetype s_gretelchase1s = {false,SPR_GRETEL_W1,3,NULL,NULL,&s_gretelchase2}; +statetype s_gretelchase2 = {false,SPR_GRETEL_W2,8,T_Chase,NULL,&s_gretelchase3}; +statetype s_gretelchase3 = {false,SPR_GRETEL_W3,10,T_Chase,NULL,&s_gretelchase3s}; +statetype s_gretelchase3s = {false,SPR_GRETEL_W3,3,NULL,NULL,&s_gretelchase4}; +statetype s_gretelchase4 = {false,SPR_GRETEL_W4,8,T_Chase,NULL,&s_gretelchase1}; +statetype s_greteldie1 = {false,SPR_GRETEL_DIE1,15,NULL,A_DeathScream,&s_greteldie2}; +statetype s_greteldie2 = {false,SPR_GRETEL_DIE2,15,NULL,NULL,&s_greteldie3}; +statetype s_greteldie3 = {false,SPR_GRETEL_DIE3,15,NULL,NULL,&s_greteldie4}; +statetype s_greteldie4 = {false,SPR_GRETEL_DEAD,0,NULL,NULL,&s_greteldie4}; +statetype s_gretelshoot1 = {false,SPR_GRETEL_SHOOT1,30,NULL,NULL,&s_gretelshoot2}; +statetype s_gretelshoot2 = {false,SPR_GRETEL_SHOOT2,10,NULL,T_Shoot,&s_gretelshoot3}; +statetype s_gretelshoot3 = {false,SPR_GRETEL_SHOOT3,10,NULL,T_Shoot,&s_gretelshoot4}; +statetype s_gretelshoot4 = {false,SPR_GRETEL_SHOOT2,10,NULL,T_Shoot,&s_gretelshoot5}; +statetype s_gretelshoot5 = {false,SPR_GRETEL_SHOOT3,10,NULL,T_Shoot,&s_gretelshoot6}; +statetype s_gretelshoot6 = {false,SPR_GRETEL_SHOOT2,10,NULL,T_Shoot,&s_gretelshoot7}; +statetype s_gretelshoot7 = {false,SPR_GRETEL_SHOOT3,10,NULL,T_Shoot,&s_gretelshoot8}; +statetype s_gretelshoot8 = {false,SPR_GRETEL_SHOOT1,10,NULL,NULL,&s_gretelchase1}; +statetype s_blinkychase1 = {false,SPR_BLINKY_W1,10,T_Ghosts,NULL,&s_blinkychase2}; +statetype s_blinkychase2 = {false,SPR_BLINKY_W2,10,T_Ghosts,NULL,&s_blinkychase1}; +statetype s_clydechase1 = {false,SPR_CLYDE_W1,10,T_Ghosts,NULL,&s_clydechase2}; +statetype s_clydechase2 = {false,SPR_CLYDE_W2,10,T_Ghosts,NULL,&s_clydechase1}; +statetype s_pinkychase1 = {false,SPR_PINKY_W1,10,T_Ghosts,NULL,&s_pinkychase2}; +statetype s_pinkychase2 = {false,SPR_PINKY_W2,10,T_Ghosts,NULL,&s_pinkychase1}; +statetype s_inkychase1 = {false,SPR_INKY_W1,10,T_Ghosts,NULL,&s_inkychase2}; +statetype s_inkychase2 = {false,SPR_INKY_W2,10,T_Ghosts,NULL,&s_inkychase1}; + +dirtype opposite[9] = + {west,southwest,south,southeast,east,northeast,north,northwest,nodir}; +dirtype diagonal[9][9] = +{ + {nodir,nodir,northeast,nodir,nodir,nodir,southeast,nodir,nodir}, + {nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir}, + {northeast,nodir,nodir,nodir,northwest,nodir,nodir,nodir,nodir}, + {nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir}, + {nodir,nodir,northwest,nodir,nodir,nodir,southwest,nodir,nodir}, + {nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir}, + {southeast,nodir,nodir,nodir,southwest,nodir,nodir,nodir,nodir}, + {nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir}, + {nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir,nodir} +}; + +/* WL_STATE.C SelectDodgeDir */ +void SelectDodgeDir (objtype *ob) +{ + int deltax,deltay,i; + int absdx,absdy; + dirtype dirtry[5]; + dirtype turnaround,tdir; + if (ob->flags & FL_FIRSTATTACK) + { + turnaround = nodir; + ob->flags &= ~FL_FIRSTATTACK; + } + else + turnaround=opposite[ob->dir]; + deltax = player.tilex - ob->tilex; + deltay = player.tiley - ob->tiley; + if (deltax>0) + { + dirtry[1]= east; + dirtry[3]= west; + } + else + { + dirtry[1]= west; + dirtry[3]= east; + } + if (deltay>0) + { + dirtry[2]= south; + dirtry[4]= north; + } + else + { + dirtry[2]= north; + dirtry[4]= south; + } + absdx = abs(deltax); + absdy = abs(deltay); + if (absdx > absdy) + { + tdir = dirtry[1]; + dirtry[1] = dirtry[2]; + dirtry[2] = tdir; + tdir = dirtry[3]; + dirtry[3] = dirtry[4]; + dirtry[4] = tdir; + } + if (US_RndT() < 128) + { + tdir = dirtry[1]; + dirtry[1] = dirtry[2]; + dirtry[2] = tdir; + tdir = dirtry[3]; + dirtry[3] = dirtry[4]; + dirtry[4] = tdir; + } + dirtry[0] = diagonal [ dirtry[1] ] [ dirtry[2] ]; + for (i=0;i<5;i++) + { + if ( dirtry[i] == nodir || dirtry[i] == turnaround) + continue; + ob->dir = dirtry[i]; + if (TryWalk(ob)) + return; + } + if (turnaround != nodir) + { + ob->dir = turnaround; + if (TryWalk(ob)) + return; + } + ob->dir = nodir; +} + +/* WL_STATE.C SelectChaseDir */ +void SelectChaseDir (objtype *ob) +{ + int deltax,deltay; + dirtype d[3]; + dirtype tdir, olddir, turnaround; + olddir=ob->dir; + turnaround=opposite[olddir]; + deltax=player.tilex - ob->tilex; + deltay=player.tiley - ob->tiley; + d[1]=nodir; + d[2]=nodir; + if (deltax>0) + d[1]= east; + else if (deltax<0) + d[1]= west; + if (deltay>0) + d[2]=south; + else if (deltay<0) + d[2]=north; + if (abs(deltay)>abs(deltax)) + { + tdir=d[1]; + d[1]=d[2]; + d[2]=tdir; + } + if (d[1]==turnaround) + d[1]=nodir; + if (d[2]==turnaround) + d[2]=nodir; + if (d[1]!=nodir) + { + ob->dir=d[1]; + if (TryWalk(ob)) + return; + } + if (d[2]!=nodir) + { + ob->dir=d[2]; + if (TryWalk(ob)) + return; + } + if (olddir!=nodir) + { + ob->dir=olddir; + if (TryWalk(ob)) + return; + } + if (US_RndT()>128) + { + for (tdir=north;tdir<=west;tdir++) + { + if (tdir!=turnaround) + { + ob->dir=tdir; + if ( TryWalk(ob) ) + return; + } + } + } + else + { + for (tdir=west;tdir>=north;tdir--) + { + if (tdir!=turnaround) + { + ob->dir=tdir; + if ( TryWalk(ob) ) + return; + } + } + } + if (turnaround != nodir) + { + ob->dir=turnaround; + if (ob->dir != nodir) + { + if ( TryWalk(ob) ) + return; + } + } + ob->dir = nodir; +} + +/* WL_STATE.C MoveObj */ +void MoveObj (objtype *ob, int32_t move) +{ + int32_t deltax,deltay; + switch (ob->dir) + { + case north: + ob->y -= move; + break; + case northeast: + ob->x += move; + ob->y -= move; + break; + case east: + ob->x += move; + break; + case southeast: + ob->x += move; + ob->y += move; + break; + case south: + ob->y += move; + break; + case southwest: + ob->x -= move; + ob->y += move; + break; + case west: + ob->x -= move; + break; + case northwest: + ob->x -= move; + ob->y -= move; + break; + case nodir: + return; + default: + return; + } + if (areabyplayer[ob->areanumber]) + { + deltax = ob->x - player.x; + if (deltax < -MINACTORDIST || deltax > MINACTORDIST) + goto moveok; + deltay = ob->y - player.y; + if (deltay < -MINACTORDIST || deltay > MINACTORDIST) + goto moveok; + + if (ob->obclass==ghostobj) TakeDamage(2,ob); + switch (ob->dir) + { + case north: + ob->y += move; + break; + case northeast: + ob->x -= move; + ob->y += move; + break; + case east: + ob->x -= move; + break; + case southeast: + ob->x -= move; + ob->y -= move; + break; + case south: + ob->y -= move; + break; + case southwest: + ob->x += move; + ob->y -= move; + break; + case west: + ob->x += move; + break; + case northwest: + ob->x += move; + ob->y += move; + break; + case nodir: + return; + } + return; + } +moveok: + ob->distance -=move; +} + +/* WL_STATE.C CheckLine */ +bool CheckLine (objtype *ob) +{ + int x1,y1,xt1,yt1,x2,y2,xt2,yt2; + int x,y; + int xdist,ydist,xstep,ystep; + + int partial,delta; + int32_t ltemp; + int xfrac,yfrac,deltafrac; + unsigned value,intercept; + x1 = ob->x >> UNSIGNEDSHIFT; + y1 = ob->y >> UNSIGNEDSHIFT; + xt1 = x1 >> 8; + yt1 = y1 >> 8; + x2 = player.x / 256; + y2 = player.y / 256; + xt2 = player.tilex; + yt2 = player.tiley; + xdist = abs(xt2-xt1); + if (xdist > 0) + { + if (xt2 > xt1) + { + partial = 256-(x1&0xff); + xstep = 1; + } + else + { + partial = x1&0xff; + xstep = -1; + } + deltafrac = abs(x2-x1); + delta = y2-y1; + ltemp = ((int32_t)delta*256)/deltafrac; + if (ltemp > 0x7fffl) + ystep = 0x7fff; + else if (ltemp < -0x7fffl) + ystep = -0x7fff; + else + ystep = ltemp; + yfrac = y1 + WL_FloorShift((int64_t)ystep*partial,8); + x = xt1+xstep; + xt2 += xstep; + do + { + y = yfrac>>8; + yfrac += ystep; + if (x<0 || y<0 || x>=64 || y>=64) return false; + value = tilemap[x][y]; + x += xstep; + if (!value) + continue; + if (value<128 || value>191) + return false; + value &= 63; + intercept = (uint16_t)(yfrac-ystep/2); + if (intercept>doorobjlist[value].position) + return false; + } while (x != xt2); + } + ydist = abs(yt2-yt1); + if (ydist > 0) + { + if (yt2 > yt1) + { + partial = 256-(y1&0xff); + ystep = 1; + } + else + { + partial = y1&0xff; + ystep = -1; + } + deltafrac = abs(y2-y1); + delta = x2-x1; + ltemp = ((int32_t)delta*256)/deltafrac; + if (ltemp > 0x7fffl) + xstep = 0x7fff; + else if (ltemp < -0x7fffl) + xstep = -0x7fff; + else + xstep = ltemp; + xfrac = x1 + WL_FloorShift((int64_t)xstep*partial,8); + y = yt1 + ystep; + yt2 += ystep; + do + { + x = xfrac>>8; + xfrac += xstep; + if (x<0 || y<0 || x>=64 || y>=64) return false; + value = tilemap[x][y]; + y += ystep; + if (!value) + continue; + if (value<128 || value>191) + return false; + value &= 63; + intercept = (uint16_t)(xfrac-xstep/2); + if (intercept>doorobjlist[value].position) + return false; + } while (y != yt2); + } + return true; +} + +/* WL_STATE.C CheckSight */ +bool CheckSight (objtype *ob) +{ + int32_t deltax,deltay; + if (!areabyplayer[ob->areanumber]) + return false; + deltax = player.x - ob->x; + deltay = player.y - ob->y; + if (deltax > -MINSIGHT && deltax < MINSIGHT + && deltay > -MINSIGHT && deltay < MINSIGHT) + return true; + switch (ob->dir) + { + case north: + if (deltay > 0) + return false; + break; + case east: + if (deltax < 0) + return false; + break; + case south: + if (deltay < 0) + return false; + break; + case west: + if (deltax > 0) + return false; + break; + } + return CheckLine (ob); +} + +/* WL_STATE.C FirstSighting */ +void FirstSighting (objtype *ob) +{ + switch (ob->obclass) + { + case guardobj: + GameSound(HALTSND,ob); + NewState (ob,&s_grdchase1); + ob->speed *= 3; + break; + case officerobj: + GameSound(SPIONSND,ob); + NewState (ob,&s_ofcchase1); + ob->speed *= 5; + break; + case mutantobj: + NewState (ob,&s_mutchase1); + ob->speed *= 3; + break; + case ssobj: + GameSound(SCHUTZADSND,ob); + NewState (ob,&s_sschase1); + ob->speed *= 4; + break; + case schabbobj:GameSound(SCHABBSHASND,NULL);NewState(ob,&s_schabbchase1);ob->speed*=3;break; + case giftobj:GameSound(EINESND,NULL);NewState(ob,&s_giftchase1);ob->speed*=3;break; + case fatobj:GameSound(ERLAUBENSND,NULL);NewState(ob,&s_fatchase1);ob->speed*=3;break; + case fakeobj:GameSound(TOT_HUNDSND,NULL);NewState(ob,&s_fakechase1);ob->speed*=3;break; + case mechahitlerobj:GameSound(DIESND,NULL);NewState(ob,&s_mechachase1);ob->speed*=3;break; + case realhitlerobj:GameSound(DIESND,NULL);NewState(ob,&s_hitlerchase1);ob->speed*=5;break; + case bossobj: + GameSound(GUTENTAGSND,NULL); + NewState(ob,&s_bosschase1);ob->speed=SPDPATROL*3; + break; + case gretelobj: + GameSound(KEINSND,NULL); + NewState(ob,&s_gretelchase1);ob->speed*=3; + break; + case dogobj: + GameSound(DOGBARKSND,ob); + NewState (ob,&s_dogchase1); + ob->speed *= 2; + break; + } + if (ob->distance < 0) + ob->distance = 0; + ob->flags |= FL_ATTACKMODE|FL_FIRSTATTACK; +} + +/* WL_STATE.C SightPlayer */ +bool SightPlayer (objtype *ob) +{ + if (ob->flags & FL_ATTACKMODE) return false; + if (ob->temp2) + { + ob->temp2 -= tics; + if (ob->temp2 > 0) + return false; + ob->temp2 = 0; + } + else + { + if (!areabyplayer[ob->areanumber]) + return false; + if (ob->flags & FL_AMBUSH) + { + if (!CheckSight (ob)) + return false; + ob->flags &= ~FL_AMBUSH; + } + else + { + if (!madenoise && !CheckSight (ob)) + return false; + } + switch (ob->obclass) + { + case guardobj: + ob->temp2 = 1+US_RndT()/4; + break; + case officerobj: + ob->temp2 = 2; + break; + case mutantobj: + ob->temp2 = 1+US_RndT()/6; + break; + case ssobj: + ob->temp2 = 1+US_RndT()/6; + break; + case dogobj: + ob->temp2 = 1+US_RndT()/8; + break; + case bossobj: + case schabbobj: + case fakeobj: + case mechahitlerobj: + case realhitlerobj: + case gretelobj: + case giftobj: + case fatobj: + case spectreobj: + case angelobj: + case transobj: + case uberobj: + case willobj: + case deathobj: + ob->temp2 = 1; + break; + } + return false; + } + FirstSighting (ob); + return true; +} + +/* WL_STATE.C DamageActor */ +void DamageActor (objtype *ob, int damage) +{ + if (!ob || !(ob->flags&FL_SHOOTABLE) || damage<0) return; + /* Damage is bounded by the original weapon rules. Saturate API outliers + before the original surprise multiplier, rather than overflowing C. */ + if (damage>32767) damage=32767; + madenoise = true; + if ( !(ob->flags & FL_ATTACKMODE) ) + damage <<= 1; + ob->hitpoints -= damage; + if (ob->hitpoints<=0) + KillActor (ob); + else + { + if (! (ob->flags & FL_ATTACKMODE) ) + FirstSighting (ob); + switch (ob->obclass) + { + case guardobj: + if (ob->hitpoints&1) + NewState (ob,&s_grdpain); + else + NewState (ob,&s_grdpain1); + break; + case officerobj: + if (ob->hitpoints&1) + NewState (ob,&s_ofcpain); + else + NewState (ob,&s_ofcpain1); + break; + case mutantobj: + if (ob->hitpoints&1) + NewState (ob,&s_mutpain); + else + NewState (ob,&s_mutpain1); + break; + case ssobj: + if (ob->hitpoints&1) + NewState (ob,&s_sspain); + else + NewState (ob,&s_sspain1); + break; + } + } +} + +/* WL_STATE.C KillActor */ +void KillActor (objtype *ob) +{ + int tilex,tiley; + tilex = ob->tilex = ob->x >> TILESHIFT; + tiley = ob->tiley = ob->y >> TILESHIFT; + switch (ob->obclass) + { + case guardobj: + GivePoints (100); + NewState (ob,&s_grddie1); + PlaceItemType (bo_clip2,tilex,tiley); + break; + case officerobj: + GivePoints (400); + NewState (ob,&s_ofcdie1); + PlaceItemType (bo_clip2,tilex,tiley); + break; + case mutantobj: + GivePoints (700); + NewState (ob,&s_mutdie1); + PlaceItemType (bo_clip2,tilex,tiley); + break; + case ssobj: + GivePoints (500); + NewState (ob,&s_ssdie1); + if (gamestate.bestweapon < wp_machinegun) + PlaceItemType (bo_machinegun,tilex,tiley); + else + PlaceItemType (bo_clip2,tilex,tiley); + break; + case schabbobj: + GivePoints(5000);gamestate.killx=player.x;gamestate.killy=player.y; + NewState(ob,&s_schabbdie1);A_DeathScream(ob);break; + case giftobj:case fatobj:case realhitlerobj: + GivePoints(5000);gamestate.killx=player.x;gamestate.killy=player.y; + NewState(ob,ob->obclass==giftobj ? &s_giftdie1 : ob->obclass==fatobj ? &s_fatdie1 : &s_hitlerdie1); + if (ob->obclass==realhitlerobj) A_DeathScream(ob); + break; + case fakeobj:GivePoints(2000);NewState(ob,&s_fakedie1);break; + case mechahitlerobj:GivePoints(5000);NewState(ob,&s_mechadie1);break; + case bossobj: + GivePoints(5000);NewState(ob,&s_bossdie1); + PlaceItemType(bo_key1,tilex,tiley); + break; + case gretelobj: + GivePoints(5000);NewState(ob,&s_greteldie1); + PlaceItemType(bo_key1,tilex,tiley); + break; + case dogobj: + GivePoints (200); + NewState (ob,&s_dogdie1); + break; + } + gamestate.killcount++; + ob->flags &= ~FL_SHOOTABLE; + /* DOS clears the actual death cell after retargeting tilex/tiley. Its + previous destination reservation can remain until overwritten. */ + actorat[ob->tilex][ob->tiley]=NULL; + ob->flags |= FL_NONMARK; +} + +/* WL_ACT2.C T_Stand */ +void T_Stand (objtype *ob) +{ + SightPlayer (ob); +} + +/* WL_ACT2.C T_Chase */ +void T_Chase (objtype *ob) +{ + int32_t move; + int dx,dy,dist,chance; + bool dodge; + if (gamestate.victoryflag) + return; + dodge = false; + if (CheckLine(ob)) + { + dx = abs(ob->tilex - player.tilex); + dy = abs(ob->tiley - player.tiley); + dist = dx>dy ? dx : dy; + if (!dist || (dist==1 && ob->distance<0x4000) ) + chance = 300; + else + chance = (tics<<4)/dist; + if ( US_RndT()obclass) + { + case guardobj: + NewState (ob,&s_grdshoot1); + break; + case officerobj: + NewState (ob,&s_ofcshoot1); + break; + case mutantobj: + NewState (ob,&s_mutshoot1); + break; + case mechahitlerobj:NewState(ob,&s_mechashoot1);break; + case realhitlerobj:NewState(ob,&s_hitlershoot1);break; + case bossobj: + NewState(ob,&s_bossshoot1); + break; + case gretelobj: + NewState(ob,&s_gretelshoot1); + break; + case ssobj: + NewState (ob,&s_ssshoot1); + break; + } + return; + } + dodge = true; + } + if (ob->dir == nodir) + { + if (dodge) + SelectDodgeDir (ob); + else + SelectChaseDir (ob); + if (ob->dir == nodir) + return; + } + move = ob->speed*tics; + while (move) + { + if (ob->distance < 0) + { + OpenDoor ((unsigned)(-ob->distance-1)); + if (doorobjlist[-ob->distance-1].action != dr_open) + return; + ob->distance = TILEGLOBAL; + } + if (move < ob->distance) + { + MoveObj (ob,move); + break; + } + ob->x = ((int32_t)ob->tilex<y = ((int32_t)ob->tiley<distance; + if (dodge) + SelectDodgeDir (ob); + else + SelectChaseDir (ob); + if (ob->dir == nodir) + return; + } +} + +/* WL_ACT2.C T_Ghosts. Ghosts are not shootable, but still reserve tiles + and use the original chase direction selection and contact damage. */ +void T_Ghosts(objtype *ob) +{ + if (ob->dir==nodir) { + SelectChaseDir(ob); + if (ob->dir==nodir) return; + } + int32_t move=ob->speed; + while (move) { + /* Bound the original negative-distance door case; do not snap through + a closed door or use a negative movement budget. */ + if (ob->distance<0) { + unsigned door=(unsigned)(-ob->distance-1); + OpenDoor(door); + if (doorobjlist[door].action!=dr_open) return; + ob->distance=TILEGLOBAL; + } + if (movedistance) { MoveObj(ob,move);break; } + ob->x=ob->tilex*TILEGLOBAL+TILEGLOBAL/2; + ob->y=ob->tiley*TILEGLOBAL+TILEGLOBAL/2; + move-=ob->distance; + SelectChaseDir(ob); + if (ob->dir==nodir) return; + } +} + +/* WL_ACT2.C T_DogChase */ +void T_DogChase (objtype *ob) +{ + int32_t move; + + int32_t dx,dy; + if (ob->dir == nodir) + { + SelectDodgeDir (ob); + if (ob->dir == nodir) + return; + } + move = ob->speed*tics; + while (move) + { + dx = player.x - ob->x; + if (dx<0) + dx = -dx; + dx -= move; + if (dx <= MINACTORDIST) + { + dy = player.y - ob->y; + if (dy<0) + dy = -dy; + dy -= move; + if (dy <= MINACTORDIST) + { + NewState (ob,&s_dogjump1); + return; + } + } + if (move < ob->distance) + { + MoveObj (ob,move); + break; + } + ob->x = ((int32_t)ob->tilex<y = ((int32_t)ob->tiley<distance; + SelectDodgeDir (ob); + if (ob->dir == nodir) + return; + } +} + +/* WL_ACT2.C SelectPathDir */ +void SelectPathDir (objtype *ob) +{ + int spot; + spot = MAPSPOT(ob->tilex,ob->tiley,1)-ICONARROWS; + if (spot>=0 && spot<8) + { + ob->dir = spot; + } + ob->distance = TILEGLOBAL; + if (!TryWalk (ob)) + ob->dir = nodir; +} + +/* WL_ACT2.C T_Path */ +void T_Path (objtype *ob) +{ + int32_t move; + + if (SightPlayer (ob)) + return; + if (ob->dir == nodir) + { + SelectPathDir (ob); + if (ob->dir == nodir) + return; + } + move = ob->speed*tics; + while (move) + { + if (ob->distance < 0) + { + OpenDoor ((unsigned)(-ob->distance-1)); + if (doorobjlist[-ob->distance-1].action != dr_open) + return; + ob->distance = TILEGLOBAL; + } + if (move < ob->distance) + { + MoveObj (ob,move); + break; + } + ob->x = ((int32_t)ob->tilex<y = ((int32_t)ob->tiley<distance; + SelectPathDir (ob); + if (ob->dir == nodir) + return; + } +} + +/* WL_ACT2.C T_Shoot */ +void T_Shoot (objtype *ob) +{ + int dx,dy,dist,hitchance,damage; + + hitchance = 128; + if (!areabyplayer[ob->areanumber]) + return; + if (!CheckLine (ob)) + return; + dx = abs(ob->tilex - player.tilex); + dy = abs(ob->tiley - player.tiley); + dist = dx>dy ? dx:dy; + if (ob->obclass == ssobj || ob->obclass == bossobj) + dist = dist*2/3; + if (thrustspeed >= RUNSPEED) + { + if (ob->flags&FL_VISABLE) + hitchance = 160-dist*16; + else + hitchance = 160-dist*8; + } + else + { + if (ob->flags&FL_VISABLE) + hitchance = 256-dist*16; + else + hitchance = 256-dist*8; + } + if (US_RndT()>2; + else if (dist<4) + damage = US_RndT()>>3; + else + damage = US_RndT()>>4; + TakeDamage (damage,ob); + } + GameSound(ob->obclass==ssobj ? SSFIRESND : + (ob->obclass==bossobj || ob->obclass==mechahitlerobj || ob->obclass==realhitlerobj) ? BOSSFIRESND : + (ob->obclass==giftobj || ob->obclass==fatobj) ? MISSILEFIRESND : NAZIFIRESND,ob); +} + +/* WL_ACT2.C T_Bite */ +void T_Bite (objtype *ob) +{ + GameSound(DOGATTACKSND,ob); + int32_t dx,dy; + + + dx = player.x - ob->x; + if (dx<0) + dx = -dx; + dx -= TILEGLOBAL; + if (dx <= MINACTORDIST) + { + dy = player.y - ob->y; + if (dy<0) + dy = -dy; + dy -= TILEGLOBAL; + if (dy <= MINACTORDIST) + { + if (US_RndT()<180) + { + TakeDamage (US_RndT()>>4,ob); + return; + } + } + } + return; +} + +/* WL_PLAY.C DoActor */ +void DoActor (objtype *ob) +{ + if (!ob || !ob->state) return; + void (*think)(objtype *); + if (!ob->active && !areabyplayer[ob->areanumber]) + return; + if (!(ob->flags&(FL_NONMARK|FL_NEVERMARK)) ) + actorat[ob->tilex][ob->tiley] = NULL; + if (!ob->ticcount) + { + think = ob->state->think; + if (think) + { + think (ob); + if (!ob->state) + { + RemoveActor(ob); + return; + } + } + if (ob->flags&FL_NEVERMARK) + return; + if ( (ob->flags&FL_NONMARK) && actorat[ob->tilex][ob->tiley]) + return; + actorat[ob->tilex][ob->tiley] = ob; + return; + } + ob->ticcount-=tics; + while ( ob->ticcount <= 0) + { + think = ob->state->action; + if (think) + { + think (ob); + if (!ob->state) + { + RemoveActor(ob); + return; + } + } + ob->state = ob->state->next; + if (!ob->state) + { + RemoveActor(ob);return; + } + if (!ob->state->tictime) + { + ob->ticcount = 0; + goto think; + } + ob->ticcount += ob->state->tictime; + } +think: + think = ob->state->think; + if (think) + { + think (ob); + if (!ob->state) + { + RemoveActor(ob);return; + } + } + if (ob->flags&FL_NEVERMARK) + return; + if ( (ob->flags&FL_NONMARK) && actorat[ob->tilex][ob->tiley]) + return; + actorat[ob->tilex][ob->tiley] = ob; +} + +/* Validate all implemented enemy animations before entering play. */ +bool ValidateActorSprites(void) +{ + static const statetype *const states[]={&s_grdstand,&s_grdpath1,&s_grdpath1s,&s_grdpath2,&s_grdpath3,&s_grdpath3s,&s_grdpath4,&s_grdpain,&s_grdpain1,&s_grdshoot1,&s_grdshoot2,&s_grdshoot3,&s_grdchase1,&s_grdchase1s,&s_grdchase2,&s_grdchase3,&s_grdchase3s,&s_grdchase4,&s_grddie1,&s_grddie2,&s_grddie3,&s_grddie4,&s_dogpath1,&s_dogpath1s,&s_dogpath2,&s_dogpath3,&s_dogpath3s,&s_dogpath4,&s_dogjump1,&s_dogjump2,&s_dogjump3,&s_dogjump4,&s_dogjump5,&s_dogchase1,&s_dogchase1s,&s_dogchase2,&s_dogchase3,&s_dogchase3s,&s_dogchase4,&s_dogdie1,&s_dogdie2,&s_dogdie3,&s_dogdead,&s_ofcstand,&s_ofcpath1,&s_ofcpath1s,&s_ofcpath2,&s_ofcpath3,&s_ofcpath3s,&s_ofcpath4,&s_ofcpain,&s_ofcpain1,&s_ofcshoot1,&s_ofcshoot2,&s_ofcshoot3,&s_ofcchase1,&s_ofcchase1s,&s_ofcchase2,&s_ofcchase3,&s_ofcchase3s,&s_ofcchase4,&s_ofcdie1,&s_ofcdie2,&s_ofcdie3,&s_ofcdie4,&s_ofcdie5,&s_mutstand,&s_mutpath1,&s_mutpath1s,&s_mutpath2,&s_mutpath3,&s_mutpath3s,&s_mutpath4,&s_mutpain,&s_mutpain1,&s_mutshoot1,&s_mutshoot2,&s_mutshoot3,&s_mutshoot4,&s_mutchase1,&s_mutchase1s,&s_mutchase2,&s_mutchase3,&s_mutchase3s,&s_mutchase4,&s_mutdie1,&s_mutdie2,&s_mutdie3,&s_mutdie4,&s_mutdie5,&s_ssstand,&s_sspath1,&s_sspath1s,&s_sspath2,&s_sspath3,&s_sspath3s,&s_sspath4,&s_sspain,&s_sspain1,&s_ssshoot1,&s_ssshoot2,&s_ssshoot3,&s_ssshoot4,&s_ssshoot5,&s_ssshoot6,&s_ssshoot7,&s_ssshoot8,&s_ssshoot9,&s_sschase1,&s_sschase1s,&s_sschase2,&s_sschase3,&s_sschase3s,&s_sschase4,&s_ssdie1,&s_ssdie2,&s_ssdie3,&s_ssdie4,&s_bossstand,&s_bosschase1,&s_bosschase1s,&s_bosschase2,&s_bosschase3,&s_bosschase3s,&s_bosschase4,&s_bossdie1,&s_bossdie2,&s_bossdie3,&s_bossdie4,&s_bossshoot1,&s_bossshoot2,&s_bossshoot3,&s_bossshoot4,&s_bossshoot5,&s_bossshoot6,&s_bossshoot7,&s_bossshoot8,&s_gretelstand,&s_gretelchase1,&s_gretelchase1s,&s_gretelchase2,&s_gretelchase3,&s_gretelchase3s,&s_gretelchase4,&s_greteldie1,&s_greteldie2,&s_greteldie3,&s_greteldie4,&s_gretelshoot1,&s_gretelshoot2,&s_gretelshoot3,&s_gretelshoot4,&s_gretelshoot5,&s_gretelshoot6,&s_gretelshoot7,&s_gretelshoot8,&s_blinkychase1,&s_blinkychase2,&s_clydechase1,&s_clydechase2,&s_pinkychase1,&s_pinkychase2,&s_inkychase1,&s_inkychase2}; + w3r_byte pixels[4096],mask[4096]; + for (unsigned i=0;irotate==1 ? 8U : state->rotate==2 ? 2U : 1U; + for (unsigned j=0;jshapenum+(state->rotate==2 ? j*4 : j); + if (!PM_DecodeSprite(shape,pixels,mask)) return false; + } + } + return ValidateBossSprites(); +} diff --git a/src/engine/WL_TEXT.c b/src/engine/WL_TEXT.c new file mode 100644 index 00000000..28cf0b43 --- /dev/null +++ b/src/engine/WL_TEXT.c @@ -0,0 +1,140 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Bounded WL_TEXT.C EndText/ShowArticle/PageLayout for the original WL6 + external end articles. Original source/licensing: docs/LICENSING.md. */ +#include "WL_DEF.h" +#include "ID_CA.h" +#include "ID_IN.h" +#include "ID_VH.h" +#include +#include +#include +#define TEXTROWS 15 +static const w3r_byte *article; +static size_t pages[64],articleend; +static unsigned pagecount,currentpage; +void ResetEndText(void) { article=NULL;pagecount=currentpage=0; } +static bool LineNumbers(size_t *cursor,size_t end,int *numbers,unsigned count) +{ + unsigned found=0;size_t at=*cursor; + while (at=count) return CA_Fail("Too many article command arguments"); + unsigned value=0; + do { + value=value*10+(unsigned)(article[at++]-'0'); + if (value>9999) return CA_Fail("Article command number overflow"); + } while (at='A' ? digit-'A'+10 : digit-'0'); + } + fontcolor=(w3r_byte)color; + } else if (command==';') { + while (at') px=160; + else if (command=='G') { + if (!LineNumbers(&at,end,args,3) || !VWB_DrawPic(args[1],args[0],args[2])) return false; + int width=pictable[args[2]-STARTPICS].width,height=pictable[args[2]-STARTPICS].height; + int top=(args[0]-16)/10,bottom=(args[0]+height-16)/10; + if (top<0) top=0; + if (bottom>=TEXTROWS) bottom=TEXTROWS-1; + bool rhs=args[1]+width/2>160; + for (int i=top;i<=bottom;++i) { + if (rhs) right[i]=args[1]-8;else left[i]=args[1]+width+8; + } + if (px=166 || args[1]>304) + return CA_Fail("Invalid article text location"); + row=(unsigned)(args[0]-16)/10;py=16+(int)row*10;px=args[1]; + } else if (command=='B') { + if (!LineNumbers(&at,end,args,4) || args[1]>320-args[2] || args[0]>200-args[3]) + return CA_Fail("Invalid article rectangle"); + VWB_Bar(args[1],args[0],args[2],args[3],0x11); + } else return CA_Fail("Unsupported article command %c",(int)command); + } else if (ch=='\n') { + if (++row==TEXTROWS) break; + py+=10;px=left[row]; + } else if (ch=='\t') px=(px+8)&0xf8; + else if (ch>32) { + char word[80];unsigned length=0;word[length++]=(char)ch; + while (at32) { + if (length==sizeof(word)-1) return CA_Fail("Article word exceeds original limit"); + word[length++]=(char)article[at++]; + } + word[length]=0;int width,height; + if (!VW_MeasurePropString(word,&width,&height)) return false; + while (px+width>right[row]) { + if (++row==TEXTROWS) break; + py+=10;px=left[row]; + } + if (row==TEXTROWS) break; + int next=px+width; + if (!VW_DrawPropString(word)) return false; + px=next; + while (at30000) return CA_Fail("Article exceeds original scan limit"); + size_t first=0;while (first +#include +#include +#define BJRUNSPEED 2048 +#define BJJUMPSPEED 680 +static objtype *camactor; +static unsigned camphase,camwait; +static uint32_t camrnd; +static w3r_byte replay[320*160]; +static void T_BJRun(objtype *ob); +static void T_BJJump(objtype *ob); +static void T_BJDone(objtype *ob); +static void T_BJYell(objtype *ob); +extern statetype s_bjrun1,s_bjrun1s,s_bjrun2,s_bjrun3,s_bjrun3s,s_bjrun4; +extern statetype s_bjjump1,s_bjjump2,s_bjjump3,s_bjjump4; +statetype s_deathcam = {false,0,0,NULL,NULL,NULL}; +statetype s_bjrun1 = {false,SPR_BJ_W1,12,T_BJRun,NULL,&s_bjrun1s}; +statetype s_bjrun1s = {false,SPR_BJ_W1,3,NULL,NULL,&s_bjrun2}; +statetype s_bjrun2 = {false,SPR_BJ_W2,8,T_BJRun,NULL,&s_bjrun3}; +statetype s_bjrun3 = {false,SPR_BJ_W3,12,T_BJRun,NULL,&s_bjrun3s}; +statetype s_bjrun3s = {false,SPR_BJ_W3,3,NULL,NULL,&s_bjrun4}; +statetype s_bjrun4 = {false,SPR_BJ_W4,8,T_BJRun,NULL,&s_bjrun1}; +statetype s_bjjump1 = {false,SPR_BJ_JUMP1,14,T_BJJump,NULL,&s_bjjump2}; +statetype s_bjjump2 = {false,SPR_BJ_JUMP2,14,T_BJJump,T_BJYell,&s_bjjump3}; +statetype s_bjjump3 = {false,SPR_BJ_JUMP3,14,T_BJJump,NULL,&s_bjjump4}; +statetype s_bjjump4 = {false,SPR_BJ_JUMP4,300,NULL,T_BJDone,&s_bjjump4}; +void ResetVictory(void) { camactor=NULL;camphase=camwait=0; } +bool DeathCameraActive(void) { return camphase!=0; } +bool VictoryTile(void) +{ + if (gamestate.victoryflag) return true; + objtype *ob=SpawnActor(player.tilex,player.tiley+1,&s_bjrun1); + if (!ob) return false; + ob->x=player.x;ob->y=player.y;ob->obclass=bjobj; + ob->dir=north;ob->temp1=6;gamestate.victoryflag=true;return true; +} +void VictorySpin(void) +{ + if (player.angle>270) { player.angle-=3;if (player.angle<270) player.angle=270; } + else if (player.angle<270) { player.angle+=3;if (player.angle>270) player.angle=270; } + int32_t dest=(player.tiley-5)*TILEGLOBAL-0x3000; + /* Invalid victory routes cannot drive the camera out of the map. */ + if (destdest) { player.y-=4096;if (player.ydistance) { MoveObj(ob,move);break; } + ob->x=ob->tilex*TILEGLOBAL+TILEGLOBAL/2; + ob->y=ob->tiley*TILEGLOBAL+TILEGLOBAL/2; + move-=ob->distance;SelectPathDir(ob); + if (!--ob->temp1) { NewState(ob,&s_bjjump1);return; } + if (ob->dir==nodir) return; + } +} +static void T_BJJump(objtype *ob) { MoveObj(ob,BJJUMPSPEED); } +static void T_BJYell(objtype *ob) { GameSound(YEAHSND,ob); } +static void T_BJDone(objtype *ob) { (void)ob;playstate=ex_victorious; } +void A_StartDeathCam(objtype *ob) +{ + if (camphase || gamestate.died) return; + FinishPaletteShifts();camactor=ob;camphase=gamestate.victoryflag ? 4U : 1U;camwait=100; +} +/* Original CheckPosition ignores live actors, but tests the complete physical + camera square against wall/static sentinels. Bounds replace DOS overreads. */ +static bool CameraPosition(void) +{ + int xl=WL_FloorShift((int64_t)player.x-MINDIST,16),xh=WL_FloorShift((int64_t)player.x+MINDIST,16); + int yl=WL_FloorShift((int64_t)player.y-MINDIST,16),yh=WL_FloorShift((int64_t)player.y+MINDIST,16); + if (xl<0 || yl<0 || xh>=64 || yh>=64) return false; + for (int x=xl;x<=xh;++x) for (int y=yl;y<=yh;++y) { + unsigned tile=tilemap[x][y]; + if (staticblock[x][y] || (tile && tile!=64 && (!(tile&128) || (tile&64) || DoorSolid(tile&63)))) return false; + } + return true; +} +bool StepDeathCamera(void) +{ + if (!camphase) return true; + if (camphase==5) { + /* WL_DRAW.C fizzlein: 20-frame budget, restricted to the viewport. */ + for (unsigned i=0;i<64000/20;++i) { + unsigned x=camrnd>>8,y=(camrnd-1)&255U; + camrnd=(camrnd>>1)^((camrnd&1U)?UINT32_C(0x12000):0U); + if (x>8,y=(camrnd-1)&255U; + camrnd=(camrnd>>1)^((camrnd&1U)?UINT32_C(0x12000):0U); + if (x<320 && y<160) framebuffer[y*320+x]=127; + if (camrnd==1) { + camphase=3;camwait=300;IN_ClearKeysDown(); + return DrawDeathCameraMessage(); + } + } + return true; + } + if (--camwait && !IN_AnyPressed()) return true; + float angle=(float)atan2((double)gamestate.killy-camactor->y,(double)camactor->x-gamestate.killx); + if (angle<0) angle=(float)(angle+6.28318530717958647692); + player.angle=((int)(angle/6.28318530717958647692*360))%ANGLES; + bool found=false; + for (int32_t dist=0x14000;dist<64*TILEGLOBAL;dist+=0x1000) { + player.x=camactor->x-FixedByFrac(dist,sintable[player.angle+90]); + player.y=camactor->y+FixedByFrac(dist,sintable[player.angle]); + if (CameraPosition()) { found=true;break; } + } + if (!found) return CA_Fail("No valid boss death-camera position"); + player.tilex=player.x/TILEGLOBAL;player.tiley=player.y/TILEGLOBAL;player.state=&s_deathcam;player.temp1=0; + switch (camactor->obclass) { + case schabbobj:NewState(camactor,&s_schabbdeathcam);break; + case giftobj:NewState(camactor,&s_giftdeathcam);break; + case fatobj:NewState(camactor,&s_fatdeathcam);break; + case realhitlerobj:NewState(camactor,&s_hitlerdeathcam);break; + default:return CA_Fail("Invalid death-camera actor"); + } + IN_ClearKeysDown();memcpy(replay,framebuffer,sizeof(replay)); + DrawPlayBorder();if (!UpdatePaletteShifts() || !ThreeDRefresh()) return false; + for (unsigned y=0;y19) return CA_Fail("View size must be 4 through 19"); + viewwidth=(uint16_t)(size*16);viewheight=(uint16_t)(size*8); + viewxorigin=(uint16_t)((320-viewwidth)/2);viewyorigin=(uint16_t)((160-viewheight)/2); + CalcProjection();return true; +} +static bool DrawPreview(void) +{ + unsigned old=ViewSize(); + if(!NewViewSize(preview)) return false; + DrawPlayBorder(); + if(!NewViewSize(old)) return false; + VWB_Bar(0,160,320,40,127);fontnumber=1;fontcolor=HIGHLIGHT; + static const char *const lines[]={"Use arrows to size","ENTER to accept","ESC to cancel"}; + for(unsigned i=0;i<3;++i) { + int w,h;if(!VW_MeasurePropString(lines[i],&w,&h)) return false; + PrintX=(320-w)/2;PrintY=161+(int)i*h;if(!US_Print(lines[i])) return false; + } + return true; +} +bool BeginViewMenu(void) { preview=ViewSize();repeat=0;IN_ClearKeysDown();return DrawPreview(); } +int HandleViewMenu(uint64_t ticks) +{ + if(IN_ConsumePress(sc_Escape)) { (void)SD_PlaySound(ESCPRESSEDSND,0,0);return -1; } + if(IN_ConsumePress(sc_Enter)) { + if(!NewViewSize(preview)) return -3; + (void)SD_PlaySound(SHOOTSND,0,0);return 1; + } + bool smaller=IN_ConsumePress(sc_LeftArrow)|IN_ConsumePress(sc_DownArrow); + bool larger=IN_ConsumePress(sc_RightArrow)|IN_ConsumePress(sc_UpArrow); + if(!smaller && !larger && ticks>=repeat) { + smaller=Keyboard[sc_LeftArrow] || Keyboard[sc_DownArrow]; + larger=Keyboard[sc_RightArrow] || Keyboard[sc_UpArrow]; + } + if(smaller || larger) { + if(smaller && preview>4) --preview;else if(!smaller && preview<19) ++preview; + repeat=ticks+10;(void)SD_PlaySound(HITWALLSND,0,0);return DrawPreview()?0:-3; + } + return 0; +} diff --git a/src/engine/gamepal.inc b/src/engine/gamepal.inc new file mode 100644 index 00000000..17d495b1 --- /dev/null +++ b/src/engine/gamepal.inc @@ -0,0 +1,33 @@ +/* Original 6-bit VGA gamepal from WOLFSRC/OBJ/GAMEPAL.OBJ LEDATA. */ +0, 0, 0, 0, 0, 42, 0, 42, 0, 0, 42, 42, 42, 0, 0, 42, 0, 42, 42, 21, 0, 42, 42, 42, +21, 21, 21, 21, 21, 63, 21, 63, 21, 21, 63, 63, 63, 21, 21, 63, 21, 63, 63, 63, 21, 63, 63, 63, +59, 59, 59, 55, 55, 55, 52, 52, 52, 48, 48, 48, 45, 45, 45, 42, 42, 42, 38, 38, 38, 35, 35, 35, +31, 31, 31, 28, 28, 28, 25, 25, 25, 21, 21, 21, 18, 18, 18, 14, 14, 14, 11, 11, 11, 8, 8, 8, +63, 0, 0, 59, 0, 0, 56, 0, 0, 53, 0, 0, 50, 0, 0, 47, 0, 0, 44, 0, 0, 41, 0, 0, +38, 0, 0, 34, 0, 0, 31, 0, 0, 28, 0, 0, 25, 0, 0, 22, 0, 0, 19, 0, 0, 16, 0, 0, +63, 54, 54, 63, 46, 46, 63, 39, 39, 63, 31, 31, 63, 23, 23, 63, 16, 16, 63, 8, 8, 63, 0, 0, +63, 42, 23, 63, 38, 16, 63, 34, 8, 63, 30, 0, 57, 27, 0, 51, 24, 0, 45, 21, 0, 39, 19, 0, +63, 63, 54, 63, 63, 46, 63, 63, 39, 63, 63, 31, 63, 62, 23, 63, 61, 16, 63, 61, 8, 63, 61, 0, +57, 54, 0, 51, 49, 0, 45, 43, 0, 39, 39, 0, 33, 33, 0, 28, 27, 0, 22, 21, 0, 16, 16, 0, +52, 63, 23, 49, 63, 16, 45, 63, 8, 40, 63, 0, 36, 57, 0, 32, 51, 0, 29, 45, 0, 24, 39, 0, +54, 63, 54, 47, 63, 46, 39, 63, 39, 32, 63, 31, 24, 63, 23, 16, 63, 16, 8, 63, 8, 0, 63, 0, +0, 63, 0, 0, 59, 0, 0, 56, 0, 0, 53, 0, 1, 50, 0, 1, 47, 0, 1, 44, 0, 1, 41, 0, +1, 38, 0, 1, 34, 0, 1, 31, 0, 1, 28, 0, 1, 25, 0, 1, 22, 0, 1, 19, 0, 1, 16, 0, +54, 63, 63, 46, 63, 63, 39, 63, 63, 31, 63, 62, 23, 63, 63, 16, 63, 63, 8, 63, 63, 0, 63, 63, +0, 57, 57, 0, 51, 51, 0, 45, 45, 0, 39, 39, 0, 33, 33, 0, 28, 28, 0, 22, 22, 0, 16, 16, +23, 47, 63, 16, 44, 63, 8, 42, 63, 0, 39, 63, 0, 35, 57, 0, 31, 51, 0, 27, 45, 0, 23, 39, +54, 54, 63, 46, 47, 63, 39, 39, 63, 31, 32, 63, 23, 24, 63, 16, 16, 63, 8, 9, 63, 0, 1, 63, +0, 0, 63, 0, 0, 59, 0, 0, 56, 0, 0, 53, 0, 0, 50, 0, 0, 47, 0, 0, 44, 0, 0, 41, +0, 0, 38, 0, 0, 34, 0, 0, 31, 0, 0, 28, 0, 0, 25, 0, 0, 22, 0, 0, 19, 0, 0, 16, +10, 10, 10, 63, 56, 13, 63, 53, 9, 63, 51, 6, 63, 48, 2, 63, 45, 0, 45, 8, 63, 42, 0, 63, +38, 0, 57, 32, 0, 51, 29, 0, 45, 24, 0, 39, 20, 0, 33, 17, 0, 28, 13, 0, 22, 10, 0, 16, +63, 54, 63, 63, 46, 63, 63, 39, 63, 63, 31, 63, 63, 23, 63, 63, 16, 63, 63, 8, 63, 63, 0, 63, +56, 0, 57, 50, 0, 51, 45, 0, 45, 39, 0, 39, 33, 0, 33, 27, 0, 28, 22, 0, 22, 16, 0, 16, +63, 58, 55, 63, 56, 52, 63, 54, 49, 63, 53, 47, 63, 51, 44, 63, 49, 41, 63, 47, 39, 63, 46, 36, +63, 44, 32, 63, 41, 28, 63, 39, 24, 60, 37, 23, 58, 35, 22, 55, 34, 21, 52, 32, 20, 50, 31, 19, +47, 30, 18, 45, 28, 17, 42, 26, 16, 40, 25, 15, 39, 24, 14, 36, 23, 13, 34, 22, 12, 32, 20, 11, +29, 19, 10, 27, 18, 9, 23, 16, 8, 21, 15, 7, 18, 14, 6, 16, 12, 6, 14, 11, 5, 10, 8, 3, +24, 0, 25, 0, 25, 25, 0, 24, 24, 0, 0, 7, 0, 0, 11, 12, 9, 4, 18, 0, 18, 20, 0, 20, +0, 0, 13, 7, 7, 7, 19, 19, 19, 23, 23, 23, 16, 16, 16, 12, 12, 12, 13, 13, 13, 54, 61, 61, +46, 58, 58, 39, 55, 55, 29, 50, 50, 18, 48, 48, 8, 45, 45, 8, 44, 44, 0, 41, 41, 0, 38, 38, +0, 35, 35, 0, 33, 33, 0, 31, 31, 0, 30, 30, 0, 29, 29, 0, 28, 28, 0, 27, 27, 38, 0, 34, diff --git a/src/main.c b/src/main.c new file mode 100644 index 00000000..4c4e77d4 --- /dev/null +++ b/src/main.c @@ -0,0 +1,175 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Entry point for the original engine UI/attract slice. */ +#include "engine/ID_CA.h" +#include "engine/ID_VL.h" +#include "platform/sdl_video.h" +#include "platform/sdl_audio.h" +#include "platform/config_file.h" +#include "engine/ID_SD.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_MENU.h" +#include "engine/WL_DEF.h" +#include "engine/WL_SAVE.h" +#include "engine/WL_HIGHSCORES.h" +#include "engine/WL_DISPLAY.h" +#include "engine/WL_FRAME_CLOCK.h" +#include +#include +#include +#include +#include +#include +#include +#include + +static void Usage(const char *name) +{ + printf("Usage: %s --data /path/to/WL6 [--check-assets|--check-ui|--check-level] [--menu|--level] [--no-audio] [--jukebox] [--goobers] [--frames N] [--capture local.bmp]\n" + "Original WL6 campaign with native AdLib music and digitized audio. New Game selects episode and difficulty.\n" + "--check-assets/--check-ui/--check-level validate without a window.\n" + "--level starts E1M1 directly; arrows move/turn, Alt strafes, Shift runs.\n" + "Ctrl fires; 1-4 select weapons; Space uses doors, pushwalls and elevators; Escape returns to menu. --frames limits a smoke test.\n", + name); +} + +int main(int argc, char *argv[]) +{ + const char *directory = NULL, *capture = NULL; + bool no_audio=false,config_writable=false,jukebox=false; + char *save_path=NULL; + bool check_only = false, check_ui = false, check_level = false, menu = false, level = false; + unsigned long frames = 0; + int status = 1; + for (int i = 1; i < argc; ++i) { + if (strcmp(argv[i], "--jukebox")==0) { jukebox=true;continue; } + if (strcmp(argv[i], "--goobers")==0) { DemoLoopAllowDebug(true);continue; } + if (strcmp(argv[i], "--no-audio") == 0) { no_audio=true;continue; } + if (strcmp(argv[i], "--help") == 0) { Usage(argv[0]); return 0; } + if (strcmp(argv[i], "--check-level") == 0) { check_level = true; continue; } + if (strcmp(argv[i], "--level") == 0) { level = true; continue; } + if (strcmp(argv[i], "--menu") == 0) { menu = true; continue; } + if (strcmp(argv[i], "--check-ui") == 0) { check_ui = true; continue; } + if (strcmp(argv[i], "--check-assets") == 0) { check_only = true; continue; } + if (strcmp(argv[i], "--data") == 0 && i + 1 < argc) { directory = argv[++i]; continue; } + if (strcmp(argv[i], "--capture") == 0 && i + 1 < argc) { capture = argv[++i]; continue; } + if (strcmp(argv[i], "--frames") == 0 && i + 1 < argc) { + char *end; + const char *value = argv[++i]; + errno = 0; + frames = strtoul(value, &end, 10); + if (!errno && value[0] >= '0' && value[0] <= '9' && !*end && frames > 0 && frames <= 100000) + continue; + } + fprintf(stderr, "Invalid/incomplete option: %s\n", argv[i]); + Usage(argv[0]); + return 1; + } + if (!directory || ((unsigned)check_only+(unsigned)check_ui+(unsigned)check_level>1) || (menu && level) || ((check_only || check_ui || check_level) && capture)) { + fputs("Supply --data; choose one check mode; --capture requires a window.\n", stderr); + Usage(argv[0]); + return 1; + } + MM_Startup(); + if (!CA_Startup(directory) || !VL_SetPalette(gamepal, sizeof(gamepal)) || !CA_CacheScreen(TITLEPIC)) { + fprintf(stderr, "Cannot load WL6 title: %s\n", CA_Error()); + goto done; + } + puts("Loaded original WL6 TITLEPIC: 320x200 indexed pixels, 256-color VGA palette."); + if (check_only) { status = 0; goto done; } + if (check_ui) { + if (!DemoLoopStartup(0,menu)) { fprintf(stderr,"Cannot load original UI: %s\n",CA_Error()); goto done; } + puts("Original fonts, menu pictures, credits and high scores validated."); + status = 0; goto done; + } + SD_SetDigitizedMode(true); /* Logical mode also applies with --no-audio. */ + bool ready=GameProbe(); + if (check_level) { + if (!ready) { fprintf(stderr,"Cannot load E1M1: %s\n",CA_Error()); goto done; } + puts("E1M1 maps, textures, sprites, objects, actors, HUD and original renderer validated."); + status=0; goto done; + } + MainMenu[newgame].active=ready ? 1 : 0; + if (ready) MainItems.curpos=newgame; + else { fprintf(stderr,"New Game unavailable: %s\n",CA_Error()); if (level) goto done; } + if (!VL_Startup()) { fprintf(stderr, "SDL3 video: %s\n", VL_Error()); goto video_done; } + if (!no_audio && !Audio_Startup()) fprintf(stderr,"Audio unavailable: %s; continuing silently.\n",Audio_Error()); + Display_Connect(VL_DisplayGet,VL_DisplaySet); + MainMenu[soundmenu].active=1; + save_path=SDL_GetPrefPath(NULL,"wolf3d-revive"); + if(save_path) { + if(!HighScores_Load(save_path)) fprintf(stderr,"High scores: %s\n",CA_Error()); + (void)Save_SetDirectory(save_path);config_result config=Config_Load(save_path); + config_writable=config==CONFIG_MISSING || config==CONFIG_LOADED; + if(*Config_Error()) fprintf(stderr,"Configuration: %s\n",Config_Error()); + } + else fputs("Save storage unavailable; gameplay remains available.\n",stderr); + /* Detect the historical held-M startup route before clearing menu input. */ + if(VL_PollQuit()) { status=0;goto video_done; } + const bool *keys=SDL_GetKeyboardState(NULL);jukebox=jukebox || keys[SDL_SCANCODE_M]; + DemoLoopStartupDevices(SDL_HasMouse(),SD_Ready(),SD_Ready() && SD_DigitizedMode()); + uint64_t ticks = VL_GetTicks70(); + if (!DemoLoopStartup(ticks,menu)) { fprintf(stderr,"Cannot load original UI: %s\n",CA_Error()); goto video_done; } + if(!menu && !level && !DemoLoopIntro(ticks)) { fprintf(stderr,"Startup artwork: %s\n",CA_Error());goto video_done; } + if(!menu && !level) { + char signon_path[4096]; + int n=snprintf(signon_path,sizeof(signon_path),"%s/SIGNON.RAW",directory); + if(n<0 || (size_t)n>=sizeof(signon_path)) { + fputs("Sign-on artwork path is too long.\n",stderr);goto video_done; + } + if(!DemoLoopSignon(signon_path,ticks)) { + fprintf(stderr,"Sign-on artwork: %s\n",CA_Error());goto video_done; + } + } + if(jukebox && !menu && !level && !DemoLoopJukebox(ticks,(unsigned)((ticks/7U)%3U))) goto video_done; + if (level && !DemoLoopStartGame(ticks)) { fprintf(stderr,"E1M1: %s\n",CA_Error()); goto video_done; } + if (capture) { + w3r_byte saved[768]; memcpy(saved,palette,sizeof(saved)); + (void)VL_SetPalette(gamepal,sizeof(gamepal)); + bool captured = VL_Capture(capture); + (void)VL_SetPalette(saved,sizeof(saved)); + if (!captured) { fprintf(stderr,"Cannot capture screen: %s\n",VL_Error()); goto video_done; } + } + uint64_t completed_tick=ticks,next_frame=0; + bool scheduled_before=false;double previous_refresh=0.0;unsigned long frame=0; + while(!VL_PollQuit() && DemoLoopState()!=UI_DONE) { + display_settings display={0};bool scheduled=VL_DisplayGet(&display) && display.high_resolution && display.smooth; + uint64_t now=SDL_GetTicksNS(); + double refresh=scheduled?VL_MonitorRefreshRate():60.0; + if(scheduled!=scheduled_before || refresh!=previous_refresh) { + next_frame=0;scheduled_before=scheduled;previous_refresh=refresh; + } + /* Simulation uses rational 70 Hz deadlines in every display mode. + A bounded batch retains debt; only presentation frames may be missed. */ + for(unsigned steps=0;steps<8 && WL_TickNext(&completed_tick,now);++steps) { + if(!DemoLoop(completed_tick)) { fprintf(stderr,"Original UI: %s\n",CA_Error());goto video_done; } + } + Audio_Pump(); + now=SDL_GetTicksNS(); + if(!scheduled || now>=next_frame) { + if(!VW_UpdateScreen()) { fprintf(stderr,"SDL3 presentation: %s\n",VL_Error());goto video_done; } + ++frame;if(frames && frame>=frames) break; + next_frame=WL_PresentationDeadline(now,SDL_GetTicksNS(),refresh,VL_VSyncPaced(refresh)); + } + if(!scheduled) VL_Sleep(4); + else { + now=SDL_GetTicksNS();uint64_t wake=WL_TickNS(completed_tick+1); + if(next_framenow) SDL_DelayNS(wake-now>4000000?4000000:wake-now); + } + } + status = 0; +video_done: + DemoLoopPrepareExit(); + if(save_path) { + if(status==0 && config_writable && !Config_Save(save_path)) fprintf(stderr,"Configuration: %s\n",Config_Error()); + SDL_free(save_path); + } + Display_Connect(NULL,NULL); + Audio_Shutdown(); + VL_Shutdown(); +done: + GameStop(); + CA_Shutdown(); + MM_Shutdown(); + return status; +} diff --git a/src/platform/config_file.c b/src/platform/config_file.c new file mode 100644 index 00000000..0544886f --- /dev/null +++ b/src/platform/config_file.c @@ -0,0 +1,270 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Bounded fixed-schema TOML subset. Parse completely before changing settings; + output uses the shared same-directory, synced atomic replacement primitive. */ +#include "config_file.h" +#include "save_file.h" +#include "sdl_video.h" +#include "engine/WL_CONTROLS.h" +#include "engine/WL_DEF.h" +#include "engine/WL_RENDER.h" +#include "engine/ID_SD.h" +#include +#include +#include +#include +#include +#include +#define MAX_FILE 65536U +#define MAX_RECORDS 256U +#define NAME_SIZE 64U +static char error[256]; +const char *Config_Error(void) { return error; } +static bool Error(const char *message) { (void)snprintf(error,sizeof(error),"%s",message);return false; } +static void Warn(const char *section,const char *key) +{ if(!*error) (void)snprintf(error,sizeof(error),"Ignored unsupported/conflicting %s.%s",section,key); } +static bool Path(char dst[4096],const char *dir) +{ + if(!dir || !*dir) return Error("Configuration directory unavailable"); + size_t n=strlen(dir);if(n>4000) return Error("Configuration path too long"); + int written=snprintf(dst,4096,"%s%sconfig.toml",dir,dir[n-1]=='/' || dir[n-1]=='\\'?"":"/"); + return (written>0 && written<4050) || Error("Configuration path too long"); +} +typedef enum { INTEGER,BOOLEAN,STRING } value_type; +typedef struct { char section[NAME_SIZE],key[NAME_SIZE],text[NAME_SIZE];value_type type;int64_t number; } record; +static char *Space(char *s) { while(*s==' ' || *s=='\t') ++s;return s; } +static bool End(char *s) { s=Space(s);return !*s || *s=='#'; } +static bool Bare(char **source,char name[NAME_SIZE]) +{ + char *s=*source;size_t n=0; + while((*s>='a' && *s<='z') || (*s>='A' && *s<='Z') || (*s>='0' && *s<='9') || *s=='_' || *s=='-') { + if(n==NAME_SIZE-1) return false; + name[n++]=*s++; + } + name[n]=0;*source=s;return n!=0; +} +static bool UTF8(const unsigned char *s,size_t length) +{ + for(size_t i=0;i=0xc2 && c<=0xdf) { need=1;value=c&31U;minimum=128; } + else if(c>=0xe0 && c<=0xef) { need=2;value=c&15U;minimum=2048; } + else if(c>=0xf0 && c<=0xf4) { need=3;value=c&7U;minimum=65536; } + else return false; + if(need>length-i) return false; + while(need--) { c=s[i++];if((c&0xc0U)!=0x80) return false;value=(value<<6)|(c&63U); } + if(value0x10ffff || (value>=0xd800 && value<=0xdfff)) return false; + } + return true; +} +static int Hex(unsigned c) { return c>='0' && c<='9'?(int)(c-'0'):c>='a' && c<='f'?(int)(c-'a'+10):c>='A' && c<='F'?(int)(c-'A'+10):-1; } +static bool String(char **source,char out[NAME_SIZE]) +{ + char *s=*source,quote=*s++;size_t n=0; + while(*s && *s!=quote) { + unsigned c=(unsigned char)*s++; + if(c<32 || c==127) return false; + if(c=='\\' && quote=='"') { + c=(unsigned char)*s++;if(!c) return false; + const char *esc="\"\\bfnrt",*replacement="\"\\\b\f\n\r\t",*at=strchr(esc,(int)c); + if(at) c=(unsigned char)replacement[at-esc]; + else if(c=='u' || c=='U') { + unsigned count=c=='u'?4U:8U,value=0; + for(unsigned i=0;i0x10ffff || (value>=0xd800 && value<=0xdfff) || !value) return false; + unsigned bytes=value<128?1U:value<2048?2U:value<65536?3U:4U; + if(n+bytes>=NAME_SIZE) return false; + if(bytes==1) out[n++]=(char)value; + else { + out[n++]=(char)((bytes==2?0xc0U:bytes==3?0xe0U:0xf0U)|(value>>(6*(bytes-1)))); + for(unsigned j=bytes-1;j>0;--j) out[n++]=(char)(0x80U|((value>>(6*(j-1)))&63U)); + } + continue; + } else return false; + } + if(n==NAME_SIZE-1) return false; + out[n++]=(char)c; + } + if(*s!=quote) return false; + out[n]=0;*source=s+1;return true; +} +static bool Integer(char **source,int64_t *number) +{ + char *s=*source;bool negative=false,sign=*s=='+' || *s=='-'; + if(sign) negative=*s++=='-'; + unsigned base=10; + if(s[0]=='0' && (s[1]=='x' || s[1]=='o' || s[1]=='b')) { + if(sign) return false; + base=s[1]=='x'?16U:s[1]=='o'?8U:2U;s+=2; + } + bool digit_seen=false,underscore=false,leading_zero=*s=='0';unsigned digits=0; + uint64_t value=0,limit=negative?UINT64_C(9223372036854775808):INT64_MAX; + for(;;) { + if(*s=='_') { if(!digit_seen || underscore) return false;underscore=true;++s;continue; } + int digit=Hex((unsigned char)*s);if(digit<0 || (unsigned)digit>=base) break; + if(value>(limit-(unsigned)digit)/base) return false; + value=value*base+(unsigned)digit;++s;++digits;digit_seen=true;underscore=false; + } + if(!digit_seen || underscore || (base==10 && leading_zero && digits>1)) return false; + *number=negative?(value==UINT64_C(9223372036854775808)?INT64_MIN:-(int64_t)value):(int64_t)value; + *source=s;return true; +} +static bool Value(char *s,record *r) +{ + if(*s=='"' || *s=='\'') { r->type=STRING;return String(&s,r->text) && End(s); } + if(!strncmp(s,"true",4) && End(s+4)) { r->type=BOOLEAN;r->number=1;return true; } + if(!strncmp(s,"false",5) && End(s+5)) { r->type=BOOLEAN;r->number=0;return true; } + r->type=INTEGER;return Integer(&s,&r->number) && End(s); +} +static bool Parse(char *data,record records[MAX_RECORDS],unsigned *count) +{ + char section[NAME_SIZE]="",tables[64][NAME_SIZE];unsigned ntables=0,line=0; + for(char *s=data;*s;) { + char *next=strchr(s,'\n');if(next) *next++=0; + size_t length=strlen(s);if(length && s[length-1]=='\r') s[--length]=0; + ++line;if(length>1024) goto invalid; + for(size_t i=0;isection,section); + if(!Bare(&s,r->key)) goto invalid; + s=Space(s);if(*s++!='=' || !Value(Space(s),r)) goto invalid; + for(unsigned i=0;i<*count;++i) if(!strcmp(records[i].section,section) && !strcmp(records[i].key,r->key)) goto invalid; + ++*count; + } + s=next?next:s+strlen(s); + } + return true; +invalid: + (void)snprintf(error,sizeof(error),"Malformed/unsupported TOML at line %u; configuration unchanged",line);return false; +} +static const record *Find(const record *records,unsigned count,const char *section,const char *key) +{ for(unsigned i=0;itype==INTEGER && r->number>=(int64_t)low && r->number<=(int64_t)high) return (unsigned)r->number; + Warn(r->section,r->key);return fallback; +} +static bool Bool(const record *r,bool fallback) +{ if(!r) return fallback;if(r->type==BOOLEAN) return r->number!=0;Warn(r->section,r->key);return fallback; } +static bool BindingKey(const char *key,unsigned *action,unsigned *slot) +{ + if(strncmp(key,"bind_",5)) return false; + const char *s=key+5;unsigned a=0; + if(*s<'0' || *s>'9' || (*s=='0' && s[1]>='0' && s[1]<='9')) return false; + while(*s>='0' && *s<='9') { unsigned d=(unsigned)(*s++-'0');if(a>(CT_ACTIONS-1-d)/10 || d>=CT_ACTIONS) return false;a=a*10+d; } + if(*s++!='_' || (*s!='0' && *s!='1') || s[1]) return false; + *action=a;*slot=(unsigned)(*s-'0');return amouse=Bool(Find(records,count,section,"mouse_enabled"),p->mouse); + p->invert=Bool(Find(records,count,section,"invert_mouse_x"),p->invert); + p->sensitivity=Number(Find(records,count,section,"mouse_sensitivity"),p->sensitivity,1,40); + for(unsigned i=0;isection,section) || strncmp(r->key,"bind_",5)) continue; + unsigned a,slot; + if(!BindingKey(r->key,&a,&slot) || r->type!=INTEGER || r->number<0 || r->number>=CT_KEYS || + (r->number && !*SDL_GetScancodeName((SDL_Scancode)r->number))) { *invalid=true;continue; } + p->binding[a][slot]=(unsigned)r->number; + } +} +static void Apply(const record *records,unsigned count) +{ + ct_preset preset=CT_CLASSIC;const record *r=Find(records,count,"controls","preset"); + if(r) { if(r->type==STRING && !strcmp(r->text,"modern")) preset=CT_MODERN; + else if(r->type!=STRING || strcmp(r->text,"classic")) Warn("controls","preset"); } + ct_profile profiles[2]; + for(unsigned i=0;i<2;++i) { + ct_profile defaults;CT_DefaultProfile((ct_preset)i,&defaults);profiles[i]=defaults;bool invalid=false; + const char *section=i==0?"classic_controls":"modern_controls";Profile(records,count,section,&profiles[i],&invalid); + if(i==(unsigned)preset) Profile(records,count,"controls",&profiles[i],&invalid); /* Legacy active-profile keys. */ + if(invalid || !CT_ValidProfile(&profiles[i])) { memcpy(profiles[i].binding,defaults.binding,sizeof(defaults.binding));Warn(section,"bindings"); } + (void)CT_SetProfile((ct_preset)i,&profiles[i]); + } + CT_SelectPreset(preset); + unsigned music=Number(Find(records,count,"audio","music_volume"),70,0,100),effects=Number(Find(records,count,"audio","effects_volume"),85,0,100); + SD_SetVolumes(music,effects);SD_SetEnabled(Bool(Find(records,count,"audio","music_enabled"),true),Bool(Find(records,count,"audio","effects_enabled"),true)); + (void)NewViewSize(Number(Find(records,count,"classic","view_size"),15,4,19)); + display_settings d;if(VL_DisplayGet(&d)) { + d.fullscreen=Bool(Find(records,count,"display","fullscreen"),false);d.integer=Bool(Find(records,count,"display","integer_scaling"),false); + unsigned scale=Number(Find(records,count,"display","window_scale"),3,1,5); + d.width=(int)Number(Find(records,count,"display","window_width"),scale*320,1,16384); + d.height=(int)Number(Find(records,count,"display","window_height"),scale*240,1,16384);d.scale=0; + d.high_resolution=false; + const record *render=Find(records,count,"display","renderer"); + if(render) { + if(render->type==STRING && !strcmp(render->text,"high_resolution")) d.high_resolution=true; + else if(render->type!=STRING || strcmp(render->text,"original")) Warn("display","renderer"); + } + d.render_width=Number(Find(records,count,"display","render_width"),640,640,1920); + d.render_height=Number(Find(records,count,"display","render_height"),480,480,1080); + if(!((d.render_width==640 && d.render_height==480) || (d.render_width==1280 && d.render_height==720) || (d.render_width==1920 && d.render_height==1080))) { d.render_width=640;d.render_height=480;Warn("display","render_width/render_height"); } + d.render_auto=Bool(Find(records,count,"display","render_auto"),false); + d.smooth=Bool(Find(records,count,"display","smooth_rendering"),false); + d.vsync=Bool(Find(records,count,"display","vsync"),false); + d.linear=false;const record *filter=Find(records,count,"display","filter"); + if(filter) { if(filter->type==STRING && !strcmp(filter->text,"linear")) d.linear=true; + else if(filter->type!=STRING || strcmp(filter->text,"nearest")) Warn("display","filter"); } + d.aspect=0;const record *ratio=Find(records,count,"display","aspect_ratio"); + if(ratio) { + static const char *const names[]={"auto","4:3","16:9","16:10","21:9","32:9"}; + bool found=false;for(unsigned i=0;i<6;++i) if(ratio->type==STRING && !strcmp(ratio->text,names[i])) { d.aspect=i;found=true; } + if(!found) Warn("display","aspect_ratio"); + } + if(!VL_DisplaySet(&d)) (void)Error("SDL rejected restored display settings; other preferences loaded"); + } +} +config_result Config_Load(const char *dir) +{ + error[0]=0;char path[4096];if(!Path(path,dir)) return CONFIG_IO_ERROR; + FILE *file=SaveFile_Open(path); + if(!file) { if(SaveFile_Missing(path)) return CONFIG_MISSING;(void)Error("Cannot read configuration");return CONFIG_IO_ERROR; } + char *data=malloc(MAX_FILE+1);record *records=calloc(MAX_RECORDS,sizeof(*records)); + if(!data || !records) { free(data);free(records);(void)fclose(file);(void)Error("Configuration allocation failed");return CONFIG_IO_ERROR; } + size_t size=fread(data,1,MAX_FILE+1,file);bool io=ferror(file)!=0;if(fclose(file)!=0) io=true; + config_result result=CONFIG_INVALID;unsigned count=0; + if(io) { (void)Error("Configuration read failed");result=CONFIG_IO_ERROR; } + else if(size>MAX_FILE || memchr(data,0,size) || !UTF8((const unsigned char *)data,size)) (void)Error("Configuration exceeds limits or contains invalid UTF-8/NUL"); + else { + data[size]=0; + if(Parse(data,records,&count)) { + const record *version=Find(records,count,"","schema_version"); + if(version && (version->type!=INTEGER || version->number!=1)) { (void)Error("Unsupported configuration schema version");result=CONFIG_UNSUPPORTED; } + else { Apply(records,count);result=CONFIG_LOADED; } + } + } + free(records);free(data);return result; +} +static bool Append(char *out,size_t *length,const char *format,...) +{ + va_list args;va_start(args,format);int n=vsnprintf(out+*length,8192-*length,format,args);va_end(args); + if(n<0 || (size_t)n>=8192-*length) return false; + *length+=(size_t)n;return true; +} +bool Config_Save(const char *dir) +{ + error[0]=0;char path[4096],out[8192];size_t n=0;if(!Path(path,dir)) return false; + display_settings d;if(!VL_DisplayPreferences(&d)) return Error("Cannot snapshot display preferences"); + if(!Append(out,&n,"# Wolf3D Revive preferences; separate from original data and saves.\nschema_version = 1\n\n[controls]\npreset = \"%s\"\n",CT_Preset()==CT_MODERN?"modern":"classic")) return Error("Configuration output overflow"); + for(unsigned i=0;i<2;++i) { + ct_profile p;CT_GetProfile((ct_preset)i,&p); + if(!Append(out,&n,"\n[%s_controls]\nmouse_enabled = %s\ninvert_mouse_x = %s\nmouse_sensitivity = %u\n",i==0?"classic":"modern",p.mouse?"true":"false",p.invert?"true":"false",p.sensitivity)) return Error("Configuration output overflow"); + for(unsigned a=0;a +typedef enum { CONFIG_MISSING,CONFIG_LOADED,CONFIG_INVALID,CONFIG_UNSUPPORTED,CONFIG_IO_ERROR } config_result; +config_result Config_Load(const char *directory); +bool Config_Save(const char *directory); +const char *Config_Error(void); +#endif diff --git a/src/platform/data_file.c b/src/platform/data_file.c new file mode 100644 index 00000000..7add4b04 --- /dev/null +++ b/src/platform/data_file.c @@ -0,0 +1,60 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "data_file.h" +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + + +static int EqualName(const char *a, const char *b) +{ + while (*a && *b) { + if (tolower((unsigned char)*a++) != tolower((unsigned char)*b++)) return 0; + } + return *a == *b; +} + +FILE *CA_OpenDataFile(const char *directory, const char *name) +{ + if (!directory || !name) return NULL; + char path[4096], match[256] = {0}; + int count = snprintf(path, sizeof(path), "%s/%s", directory, name); + if (count < 0 || (size_t)count >= sizeof(path)) return NULL; + FILE *file = fopen(path, "rb"); + if (file) return file; + unsigned matches = 0; +#ifdef _WIN32 + struct _finddata_t entry; + count = snprintf(path, sizeof(path), "%s/*", directory); + if (count < 0 || (size_t)count >= sizeof(path)) return NULL; + intptr_t search = _findfirst(path, &entry); + if (search == -1) return NULL; + do { + const char *candidate = entry.name; +#else + DIR *search = opendir(directory); + if (!search) return NULL; + struct dirent *entry; + while ((entry = readdir(search)) != NULL) { + const char *candidate = entry->d_name; +#endif + if (EqualName(candidate, name)) { + ++matches; + if (strlen(candidate) < sizeof(match)) strcpy(match, candidate); + } +#ifdef _WIN32 + } while (_findnext(search, &entry) == 0); + (void)_findclose(search); +#else + } + (void)closedir(search); +#endif + if (matches != 1 || !match[0]) return NULL; + count = snprintf(path, sizeof(path), "%s/%s", directory, match); + return count >= 0 && (size_t)count < sizeof(path) ? fopen(path, "rb") : NULL; +} + diff --git a/src/platform/data_file.h b/src/platform/data_file.h new file mode 100644 index 00000000..5672ae3a --- /dev/null +++ b/src/platform/data_file.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef DATA_FILE_H +#define DATA_FILE_H +#include +/* Exact spelling wins; otherwise one unambiguous ASCII case-insensitive match. */ +FILE *CA_OpenDataFile(const char *directory, const char *name); +#endif diff --git a/src/platform/display_settings.h b/src/platform/display_settings.h new file mode 100644 index 00000000..6a29ecf0 --- /dev/null +++ b/src/platform/display_settings.h @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef DISPLAY_SETTINGS_H +#define DISPLAY_SETTINGS_H +#include +typedef struct { + bool fullscreen,integer,pending; + bool high_resolution; + unsigned render_width,render_height; + bool render_auto,vsync,linear,smooth; + unsigned aspect; /* 0 Auto, 1 4:3, 2 16:9, 3 16:10, 4 21:9, 5 32:9. */ + unsigned scale; /* 1..5 window-point presets; 0 means manually resized. */ + int width,height,pixel_width,pixel_height; + char error[160]; +} display_settings; +#endif diff --git a/src/platform/save_file.c b/src/platform/save_file.c new file mode 100644 index 00000000..89e655b7 --- /dev/null +++ b/src/platform/save_file.c @@ -0,0 +1,115 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#define _POSIX_C_SOURCE 200809L +#include "save_file.h" +#include +#include +#include +#include +#include +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#include +#include +static bool Wide(const char *path,wchar_t result[4096]) +{ return MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,path,-1,result,4096)>0; } +FILE *SaveFile_Open(const char *path) { wchar_t p[4096];return Wide(path,p)?_wfopen(p,L"rb"):NULL; } +bool SaveFile_Missing(const char *path) +{ + wchar_t p[4096];if(!Wide(path,p)) return false; + DWORD attr=GetFileAttributesW(p); + return attr==INVALID_FILE_ATTRIBUTES && GetLastError()==ERROR_FILE_NOT_FOUND; +} +#else +#include +FILE *SaveFile_Open(const char *path) { return fopen(path,"rb"); } +bool SaveFile_Missing(const char *path) { struct stat st;return lstat(path,&st)!=0 && errno==ENOENT; } +#endif +#ifdef WOLF3D_CONFIG_TEST +static unsigned fault; +void SaveFile_TestFailure(unsigned operation) { fault=operation; } +static bool Fail(unsigned operation) { if(fault!=operation) return false;fault=0;errno=EIO;return true; } +#else +static bool Fail(unsigned operation) { (void)operation;return false; } +#endif +bool SaveFile_WriteAtomic(const char *path,const void *bytes,size_t length,bool overwrite) +{ + if(Fail(1)) return false; + static unsigned sequence; + char temp[4096];int fd=-1; + for(unsigned attempt=0;attempt<100;++attempt) { +#ifdef _WIN32 + int n=snprintf(temp,sizeof(temp),"%s.tmp-%lu-%u",path,(unsigned long)_getpid(),++sequence); + wchar_t wp[4096]; + if(n<0 || (size_t)n>=sizeof(temp) || !Wide(temp,wp)) return false; + fd=_wopen(wp,_O_CREAT|_O_EXCL|_O_WRONLY|_O_BINARY,_S_IREAD|_S_IWRITE); +#else + int n=snprintf(temp,sizeof(temp),"%s.tmp-%lu-%u",path,(unsigned long)getpid(),++sequence); + if(n<0 || (size_t)n>=sizeof(temp)) return false; + fd=open(temp,O_CREAT|O_EXCL|O_WRONLY,0600); +#endif + if(fd>=0) break; + if(errno!=EEXIST) return false; + } + if(fd<0) return false; +#ifdef _WIN32 + FILE *file=_fdopen(fd,"wb"); +#else + FILE *file=fdopen(fd,"wb"); +#endif + bool ok=false; + if(file) { + if(Fail(2)) { (void)fwrite(bytes,1,length/2,file);ok=false; } + else ok=fwrite(bytes,1,length,file)==length; + if(ok) ok=fflush(file)==0 && !Fail(3); + if(ok && Fail(4)) ok=false; +#ifdef _WIN32 + if(ok) ok=_commit(fd)==0; +#else + if(ok) ok=fsync(fd)==0; +#endif + if(fclose(file)!=0 || Fail(5)) ok=false; + } else { +#ifdef _WIN32 + (void)_close(fd); +#else + (void)close(fd); +#endif + } + if(ok && Fail(6)) ok=false; +#ifdef _WIN32 + wchar_t source[4096],dest[4096]; + /* The temporary file exists at this point. Keep cleanup reachable even + if conversion of the final destination fails (e.g. an invalid UTF-8 + path), rather than orphaning a .tmp file beside the save slot. */ + bool source_ok=Wide(temp,source),dest_ok=Wide(path,dest); + if(!source_ok || !dest_ok) ok=false; + if(ok) ok=MoveFileExW(source,dest,MOVEFILE_WRITE_THROUGH|(overwrite?MOVEFILE_REPLACE_EXISTING:0))!=0; + if(!ok) { + if(source_ok) (void)DeleteFileW(source); + else { + /* A path accepted for _wopen should remain convertible, but + avoid leaving a temporary file on an unexpected conversion + failure by retrying with the known UTF-8 source path. */ + wchar_t retry[4096]; + if(MultiByteToWideChar(CP_UTF8,0,temp,-1,retry,4096)>0) + (void)DeleteFileW(retry); + } + } +#else + if(ok) { + /* link() supplies atomic create-if-absent when overwrite was not + approved, including a competing writer appearing after inspection. */ + ok=overwrite ? rename(temp,path)==0 : link(temp,path)==0; + } + (void)unlink(temp); + if(ok) { + char parent[4096];(void)snprintf(parent,sizeof(parent),"%s",path); + char *slash=strrchr(parent,'/');if(slash) *slash=0;else (void)strcpy(parent,"."); + int dir=open(*parent?parent:"/",O_RDONLY|O_DIRECTORY); + if(dir>=0) { (void)fsync(dir);(void)close(dir); } + } +#endif + return ok; +} diff --git a/src/platform/save_file.h b/src/platform/save_file.h new file mode 100644 index 00000000..76894821 --- /dev/null +++ b/src/platform/save_file.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef SAVE_FILE_H +#define SAVE_FILE_H +#include +#include +#include +FILE *SaveFile_Open(const char *path); +bool SaveFile_Missing(const char *path); +bool SaveFile_WriteAtomic(const char *path,const void *bytes,size_t length,bool overwrite); +#ifdef WOLF3D_CONFIG_TEST +void SaveFile_TestFailure(unsigned operation); /* Create/write/flush/sync/close/replace. */ +#endif +#endif diff --git a/src/platform/sdl_audio.c b/src/platform/sdl_audio.c new file mode 100644 index 00000000..01f3ec10 --- /dev/null +++ b/src/platform/sdl_audio.c @@ -0,0 +1,102 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Main-thread producer: no callback locks, game pointers, filesystem or + allocations in synthesis/mixing. SDL owns conversion and asynchronous IO. */ +#include "sdl_audio.h" +#include "engine/ID_SD.h" +#include "engine/ID_CA.h" +#include "engine/WL_PROFILE.h" +#include +#include +#include +static SDL_AudioStream *stream; +static uint64_t generation; +static int queue_bytes=48000*4*80/1000; +static char error[256]; +bool Audio_Active(void) { return stream!=NULL; } +#ifdef WOLF3D_DISPLAY_TEST +int Audio_TestQueuedBytes(void) { return stream?SDL_GetAudioStreamQueued(stream):-1; } +void Audio_TestQueueMS(unsigned ms) { queue_bytes=(int)(48000*4*(ms>=8 && ms<=250?ms:80)/1000);if(stream) SDL_ClearAudioStream(stream); } +unsigned Audio_TestTargetMS(void) { return (unsigned)queue_bytes/192; } +#endif +const char *Audio_Error(void) { return error; } +void Audio_Shutdown(void) +{ + if(stream) { SDL_DestroyAudioStream(stream);stream=NULL; } + SD_Shutdown();SDL_QuitSubSystem(SDL_INIT_AUDIO); +} +static SDL_AudioStream *OpenOutput(const SDL_AudioSpec *spec) +{ + SDL_AudioStream *output=SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK,spec,NULL,NULL); +#ifdef __linux__ + /* An ALSA-only SDL SDK can run on a PulseAudio/PipeWire desktop without + an ALSA "default" PCM. Try its standard pulse plugin, respecting any + explicit SDL device hint. This changes no system configuration. */ + const char *driver=SDL_GetCurrentAudioDriver(); + if(!output && driver && !strcmp(driver,"alsa") && + !SDL_GetHint(SDL_HINT_AUDIO_ALSA_DEFAULT_DEVICE) && + !SDL_GetHint(SDL_HINT_AUDIO_ALSA_DEFAULT_PLAYBACK_DEVICE)) { + if(SDL_SetHint(SDL_HINT_AUDIO_ALSA_DEFAULT_PLAYBACK_DEVICE,"pulse")) { + output=SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK,spec,NULL,NULL); + SDL_ResetHint(SDL_HINT_AUDIO_ALSA_DEFAULT_PLAYBACK_DEVICE); + } + } +#endif + return output; +} +bool Audio_Startup(void) +{ + Audio_Shutdown();error[0]=0; + if(!SD_Startup(48000)) { (void)snprintf(error,sizeof(error),"%s",CA_Error());return false; } + SDL_AudioSpec spec={SDL_AUDIO_S16,2,48000}; + if(!SDL_InitSubSystem(SDL_INIT_AUDIO) || + !(stream=OpenOutput(&spec))) { + (void)snprintf(error,sizeof(error),"%s",SDL_GetError());Audio_Shutdown();return false; + } + SDL_AudioSpec device;int period; + if(!SDL_GetAudioDeviceFormat(SDL_GetAudioStreamDevice(stream),&device,&period) || device.freq<=0 || period<=0) { + (void)snprintf(error,sizeof(error),"Cannot query audio device period");Audio_Shutdown();return false; + } + /* Two device periods plus scheduling headroom, with an 80 ms floor. + The old 24 ms target barely covered one 21.3 ms ALSA period. */ + uint64_t ms=((uint64_t)(unsigned)period*2000+(unsigned)device.freq-1)/(unsigned)device.freq+8; + if(ms<80) ms=80; + if(ms>250) { (void)snprintf(error,sizeof(error),"Audio device buffer exceeds supported latency");Audio_Shutdown();return false; } + queue_bytes=(int)(48000*4*ms/1000); + generation=SD_OutputGeneration();Audio_Pump(); + if(!stream || !SDL_ResumeAudioStreamDevice(stream)) { + if(stream) (void)snprintf(error,sizeof(error),"%s",SDL_GetError()); + Audio_Shutdown();return false; + } + return true; +} +void Audio_Pump(void) +{ + if(!stream) return; +#ifdef WOLF3D_BENCHMARK + bool changed=generation!=SD_OutputGeneration(); +#endif + if(generation!=SD_OutputGeneration()) { + if(!SDL_ClearAudioStream(stream)) { + (void)snprintf(error,sizeof(error),"%s",SDL_GetError()); + fprintf(stderr,"SDL3 audio stopped: %s; continuing silently.\n",error); + Audio_Shutdown();return; + } + generation=SD_OutputGeneration(); + } + int queued=SDL_GetAudioStreamQueued(stream); +#ifdef WOLF3D_BENCHMARK + if(queued==0 && !changed) ++WL_Profile.empty_queues; +#endif + /* Buffer in sample frames, never render-frame timestamps. The producer + is also serviced inside expensive presentation loops. Arbitrarily long + OS/driver stalls can still exhaust this deliberately bounded queue. */ + for(unsigned blocks=0;queued>=0 && queued +bool Audio_Startup(void); +void Audio_Pump(void); +void Audio_Shutdown(void); +bool Audio_Active(void); +const char *Audio_Error(void); +#ifdef WOLF3D_DISPLAY_TEST +int Audio_TestQueuedBytes(void); +void Audio_TestQueueMS(unsigned ms); +unsigned Audio_TestTargetMS(void); +#endif +#endif diff --git a/src/platform/sdl_input.c b/src/platform/sdl_input.c new file mode 100644 index 00000000..712af0ed --- /dev/null +++ b/src/platform/sdl_input.c @@ -0,0 +1,141 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "sdl_input.h" +#include "engine/ID_IN.h" +#include "engine/WL_CONTROLS.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_MENU.h" +#include +#include +#include +static bool physical[SDL_SCANCODE_COUNT],mousebuttons[8],focused=true,captured,menu_captured,capture_failed; +static SDL_Window *capture_window; +static double menu_x,menu_y; +static ui_state mouse_state; +static char capture_error[256]; +bool IN_SDLFocused(void) { return focused; } +void IN_SDLDiscardInput(void) { memset(physical,0,sizeof(physical));IN_ClearKeysDown(); } +bool IN_SDLCaptured(void) { return captured; } +const char *IN_SDLCaptureError(void) { return capture_error; } +void IN_SDLReset(void) { IN_SDLFocusLost();focused=true;capture_window=NULL;capture_error[0]=0; } +void IN_SDLFocusGained(void) { focused=true;IN_ClearKeysDown(); } +static bool PointerMenu(void); +void IN_SDLCapture(SDL_Window *window,bool gameplay,bool menus) +{ + if(window!=capture_window) capture_failed=false; + capture_window=window; + bool want=window && gameplay && focused && CT_MouseEnabled(); + bool menu=menus && window && focused && CT_MouseEnabled() && PointerMenu(); + bool relative=want || menu; + if(!relative) capture_failed=false; + if((captured==want && menu_captured==menu) || (relative && capture_failed)) return; + if(window && !SDL_SetWindowRelativeMouseMode(window,relative)) { + (void)SDL_strlcpy(capture_error,SDL_GetError(),sizeof(capture_error)); + SDL_Log("Relative mouse unavailable: %s; keyboard controls remain active",capture_error); + captured=menu_captured=false;capture_failed=true;return; + } + /* DOS recenters its mouse counters. Relative menu capture keeps the + desktop pointer hidden and avoids stopping at a screen edge, while + the original gun cursor remains the sole selection indicator. */ + captured=want;menu_captured=menu;menu_x=menu_y=0;CT_Clear(); + /* Ignore motion queued before a mode/menu/focus transition. */ + SDL_FlushEvent(SDL_EVENT_MOUSE_MOTION); +} +void IN_SDLMouseMotion(double x) { if(captured && focused) CT_MouseMotion(x); } +static bool PointerMenu(void) +{ + ui_state state=DemoLoopState(); + if(state!=mouse_state) { menu_x=menu_y=0;mouse_state=state; } + return state==UI_MENU || state==UI_EPISODE || state==UI_DIFFICULTY || state==UI_SOUND || + state==UI_CONTROLS || state==UI_DISPLAY || state==UI_VIEW || state==UI_SAVE || state==UI_LOAD || state==UI_JUKEBOX; +} +static void Pulse(unsigned scan) +{ if(!Keyboard[scan]) { IN_MenuKeyEvent(scan,true);IN_MenuKeyEvent(scan,false); } } +void IN_SDLPointerMotion(double x,double y) +{ + if(captured) { IN_SDLMouseMotion(x);return; } + if(!focused || !PointerMenu() || !CT_MouseEnabled() || !(x>=-DBL_MAX && x<=DBL_MAX && y>=-DBL_MAX && y<=DBL_MAX)) return; + menu_x+=x;menu_y+=y; + /* WL_MENU.C ReadAnyControl: strict 60-count threshold, horizontal wins. */ + unsigned scan=menu_x< -60?sc_LeftArrow:menu_x>60?sc_RightArrow:menu_y< -60?sc_UpArrow:menu_y>60?sc_DownArrow:0U; + if(scan) { Pulse(scan);menu_x=menu_y=0; } +} +void IN_SDLMouseButton(unsigned button,bool down) +{ + if(button>=8 || mousebuttons[button]==down) return; + mousebuttons[button]=down; + if(captured && focused) CT_MouseButton(button,down); + else if(focused && down) { + if(PointerMenu() && CT_MouseEnabled()) { + if(button==SDL_BUTTON_LEFT) Pulse(sc_Enter); + else if(button==SDL_BUTTON_RIGHT) Pulse(sc_Escape); + } else IN_AckEvent(); + } +} +unsigned IN_MapSDLScancode(unsigned code) +{ + static const unsigned letters[26] = {0x1e,0x30,0x2e,0x20,0x12,0x21,0x22,0x23,0x17,0x24,0x25,0x26,0x32,0x31,0x18,0x19,0x10,0x13,0x1f,0x14,0x16,0x2f,0x11,0x2d,0x15,0x2c}; + if (code >= SDL_SCANCODE_A && code <= SDL_SCANCODE_Z) return letters[code-SDL_SCANCODE_A]; + if (code >= SDL_SCANCODE_1 && code <= SDL_SCANCODE_9) return 2 + code-SDL_SCANCODE_1; + if (code >= SDL_SCANCODE_F1 && code <= SDL_SCANCODE_F10) return 0x3b + code-SDL_SCANCODE_F1; + switch (code) { + case SDL_SCANCODE_PAUSE: return sc_Pause; + case SDL_SCANCODE_0: return 0x0b; + case SDL_SCANCODE_ESCAPE: return sc_Escape; + case SDL_SCANCODE_RETURN: case SDL_SCANCODE_KP_ENTER: return sc_Enter; + case SDL_SCANCODE_SPACE: return sc_Space; + case SDL_SCANCODE_UP: case SDL_SCANCODE_KP_8: return sc_UpArrow; + case SDL_SCANCODE_DOWN: case SDL_SCANCODE_KP_2: return sc_DownArrow; + case SDL_SCANCODE_LEFT: case SDL_SCANCODE_KP_4: return sc_LeftArrow; + case SDL_SCANCODE_RIGHT: case SDL_SCANCODE_KP_6: return sc_RightArrow; + case SDL_SCANCODE_BACKSPACE: return 0x0e; + case SDL_SCANCODE_TAB: return 0x0f; + case SDL_SCANCODE_CAPSLOCK: return 0x3a; + case SDL_SCANCODE_MINUS: return 0x0c; + case SDL_SCANCODE_EQUALS: return 0x0d; + case SDL_SCANCODE_LEFTBRACKET: return 0x1a; + case SDL_SCANCODE_RIGHTBRACKET: return 0x1b; + case SDL_SCANCODE_SEMICOLON: return 0x27; + case SDL_SCANCODE_APOSTROPHE: return 0x28; + case SDL_SCANCODE_GRAVE: return 0x29; + case SDL_SCANCODE_BACKSLASH: return 0x2b; + case SDL_SCANCODE_COMMA: return 0x33; + case SDL_SCANCODE_PERIOD: return 0x34; + case SDL_SCANCODE_SLASH: return 0x35; + case SDL_SCANCODE_HOME: return 0x47; + case SDL_SCANCODE_END: return 0x4f; + case SDL_SCANCODE_DELETE: return 0x53; + case SDL_SCANCODE_LCTRL: case SDL_SCANCODE_RCTRL: return 0x1d; + case SDL_SCANCODE_LALT: case SDL_SCANCODE_RALT: return 0x38; + case SDL_SCANCODE_LSHIFT: return 0x2a; + case SDL_SCANCODE_RSHIFT: return 0x36; + default: return 0; + } +} +void IN_SDLFocusLost(void) +{ + focused=false;menu_x=menu_y=0; + if((captured || menu_captured) && capture_window) (void)SDL_SetWindowRelativeMouseMode(capture_window,false); + captured=menu_captured=false;capture_failed=false;memset(physical,0,sizeof(physical));memset(mousebuttons,0,sizeof(mousebuttons));IN_ClearKeysDown(); +} +/* DOS IRQ keyboard input delivered typematic make codes to US_LineInput. + Use native repeat events only in editors, never for gameplay or dialogs. */ +void IN_SDLRepeat(unsigned code) +{ + if(code>=SDL_SCANCODE_COUNT || !focused || !physical[code]) return; + ui_state state=DemoLoopState(); + if(state!=UI_RESULTS && state!=UI_WARP && !(state==UI_SAVE && SaveMenuEditing())) return; + unsigned scan=IN_MapSDLScancode(code); + if(!IN_ScanASCII(scan) && scan!=0x0e && scan!=0x53 && scan!=0x47 && scan!=0x4f && scan!=sc_LeftArrow && scan!=sc_RightArrow) return; + IN_MenuKeyEvent(scan,false);IN_MenuKeyEvent(scan,true); +} +void IN_SDLKey(unsigned code, bool down) +{ + if (code >= SDL_SCANCODE_COUNT || !focused || physical[code] == down) return; + physical[code] = down;CT_Key(code,down); + unsigned scan = IN_MapSDLScancode(code); + if (!scan) return; + bool held = false; + for (unsigned i = 0; i < SDL_SCANCODE_COUNT; ++i) + if (physical[i] && IN_MapSDLScancode(i) == scan) { held = true; break; } + IN_MenuKeyEvent(scan,held); +} diff --git a/src/platform/sdl_input.h b/src/platform/sdl_input.h new file mode 100644 index 00000000..b7852743 --- /dev/null +++ b/src/platform/sdl_input.h @@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef SDL_INPUT_H +#define SDL_INPUT_H +#include +#include +unsigned IN_MapSDLScancode(unsigned code); +void IN_SDLKey(unsigned code, bool down); +void IN_SDLRepeat(unsigned code); +void IN_SDLFocusLost(void); +void IN_SDLFocusGained(void); +void IN_SDLReset(void); +void IN_SDLDiscardInput(void); +bool IN_SDLFocused(void); +void IN_SDLCapture(SDL_Window *window,bool gameplay,bool menus); +void IN_SDLMouseMotion(double x); +void IN_SDLPointerMotion(double x,double y); +void IN_SDLMouseButton(unsigned button,bool down); +/* Gameplay capture; menu capture never enables gameplay mouse actions. */ +bool IN_SDLCaptured(void); +const char *IN_SDLCaptureError(void); +#endif diff --git a/src/platform/sdl_video.c b/src/platform/sdl_video.c new file mode 100644 index 00000000..32380818 --- /dev/null +++ b/src/platform/sdl_video.c @@ -0,0 +1,465 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* SDL3 presentation boundary. Original graphics decoding lives in ID_CA/VL. */ +#include "sdl_video.h" +#include "sdl_audio.h" +#include "sdl_input.h" +#include "engine/ID_TIME.h" +#include "engine/WL_CONTROLS.h" +#include "engine/ID_VL.h" +#include "engine/WL_RENDER.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_SAVE.h" +#include "engine/WL_DEMO.h" +#include "engine/WL_PROFILE.h" +#include +#include +#define SDL_MAIN_HANDLED +#include +#include +#include + +static SDL_Window *window; +static SDL_Renderer *renderer; +static SDL_Texture *texture; +static w3r_byte rgba[VL_PIXELS * 4], last_frame[VL_PIXELS], last_palette[768]; +static bool Fail(unsigned operation); +typedef struct { SDL_Texture *texture;w3r_byte *pixels,*rgba;wl_render_target target; } high_surface; +static high_surface high; +static bool high_resolution,render_auto,vsync,linear,smooth; + +static uint64_t present_ns; +static bool high_smooth; +static wl_present_snapshot presentation; +static unsigned aspect; +static Uint64 auto_retry; +static wl_rectangle high_scene; +static unsigned render_width=640,render_height=480; +static int32_t high_depth[WL_TARGET_MAX_WIDTH]; +static uint32_t high_time,high_death_cursor; +static unsigned high_death_phase; +static bool high_dying; +static uint64_t high_serial,high_uploads; +static bool high_world,high_uploaded; +static void FreeHigh(high_surface *s) +{ if(s->texture) SDL_DestroyTexture(s->texture);free(s->pixels);free(s->rgba);memset(s,0,sizeof(*s)); } +#ifdef WOLF3D_DISPLAY_TEST +static unsigned test_desktop_w,test_desktop_h; +static uint64_t surface_creations; +void VL_TestDesktopSize(unsigned w,unsigned h) { test_desktop_w=w;test_desktop_h=h;auto_retry=0; } +uint64_t VL_TestSurfaceCreations(void) { return surface_creations; } +SDL_Texture *VL_TestSceneTexture(void) { return high.texture; } +#endif +static bool RenderSize(bool automatic,unsigned *w,unsigned *h) +{ + if(!automatic) return true; +#ifdef WOLF3D_DISPLAY_TEST + if(test_desktop_w && test_desktop_h) return WL_AutoRenderSize(test_desktop_w,test_desktop_h,w,h); +#endif + const SDL_DisplayMode *desktop=SDL_GetDesktopDisplayMode(SDL_GetDisplayForWindow(window)); + if(!desktop || desktop->w<320 || desktop->h<200) return SDL_SetError("Desktop rendering dimensions unavailable"); + if(!WL_AutoRenderSize((unsigned)desktop->w,(unsigned)desktop->h,w,h)) + return SDL_SetError("Unsupported desktop aspect for automatic rendering"); + return true; +} +static bool CreateHigh(high_surface *s,unsigned w,unsigned h) +{ + memset(s,0,sizeof(*s)); + if(!WL_RenderResolution(w,h)) return SDL_SetError("Unsupported rendering resolution"); + size_t bytes=(size_t)w*h; + if(Fail(5)) return false; + s->pixels=malloc(bytes);s->rgba=malloc(bytes*4); + if(!s->pixels || !s->rgba || !WL_TargetInit(&s->target,s->pixels,bytes,w,h,w)) { + FreeHigh(s);return SDL_SetError("Cannot allocate rendering surface"); + } + if(Fail(6)) { FreeHigh(s);return false; } + s->texture=SDL_CreateTexture(renderer,SDL_PIXELFORMAT_RGBA32,SDL_TEXTUREACCESS_STREAMING,(int)w,(int)h); + if(!s->texture || !SDL_SetTextureScaleMode(s->texture,linear?SDL_SCALEMODE_LINEAR:SDL_SCALEMODE_NEAREST)) { FreeHigh(s);return false; } +#ifdef WOLF3D_DISPLAY_TEST + ++surface_creations; +#endif + return true; +} +static bool uploaded; +static uint64_t uploads; +/* Actual fullscreen state always comes from SDL flags. Only an outstanding + asynchronous request has a target; it never masquerades as actual state. */ +static bool integer_scale,pending,target,restore_size,size_pending; +static int window_w=960,window_h=720; +static Uint64 request_deadline; +static int applied_w,applied_h; +static SDL_RendererLogicalPresentation applied_mode=SDL_LOGICAL_PRESENTATION_DISABLED; +static char display_error[160]; +static bool consumed[SDL_SCANCODE_COUNT]; +#ifdef WOLF3D_DISPLAY_TEST +static unsigned fault; +uint64_t VL_TestSceneUploads(void) { return high_uploads; } +void VL_TestDisplayFailure(unsigned operation) { fault=operation; } +void VL_TestExpireDisplayRequest(void) { request_deadline=0; } +static bool Fail(unsigned operation) { if(fault!=operation) return false;fault=0;SDL_SetError("Injected display failure");return true; } +#else +static bool Fail(unsigned operation) { (void)operation;return false; } +#endif +static bool Fullscreen(void) { return window && (SDL_GetWindowFlags(window)&SDL_WINDOW_FULLSCREEN)!=0; } +static bool DisplayError(void) +{ + (void)SDL_strlcpy(display_error,SDL_GetError(),sizeof(display_error)); + SDL_Log("Display change failed: %s",display_error);return false; +} +static bool WorldPresentation(void) +{ + /* Intermission and end-text pages can live inside UI_GAME, but contain + the original DOS interface rather than a widescreen world. */ + return GameRunning() && (DemoLoopState()==UI_GAME || DemoLoopState()==UI_DEMO) && + !GameIntermission() && !GameVictoryPresentation() && !GameLoadingScreen(); +} +static bool ApplyPresentation(void) +{ + int w,h;if(!renderer || !SDL_GetRenderOutputSize(renderer,&w,&h)) return false; + /* SDL integer mode enforces at least 1x and otherwise crops tiny windows. + Fall back to fit below the corrected canvas's minimum drawable size. */ + int lw=320,lh=240; + bool world=high_resolution && WorldPresentation(); + if(world && high_scene.width) { lw=(int)high_scene.width;lh=(int)high_scene.height; } + /* Integer scaling belongs to the DOS canvas. Enhanced scenes fit the + output independently, even when the menu uses integer scaling. */ + SDL_RendererLogicalPresentation mode=!world && integer_scale && w>=lw && h>=lh? + SDL_LOGICAL_PRESENTATION_INTEGER_SCALE:SDL_LOGICAL_PRESENTATION_LETTERBOX; + if(applied_mode==mode && applied_w==lw && applied_h==lh) return true; + if(Fail(2) || !SDL_SetRenderLogicalPresentation(renderer,lw,lh,mode)) return false; + applied_mode=mode;applied_w=lw;applied_h=lh;return true; +} +static bool SettingsFailure(high_surface *candidate) +{ + char saved[160];(void)SDL_strlcpy(saved,SDL_GetError(),sizeof(saved)); + (void)SDL_SetRenderVSync(renderer,vsync?1:0); + (void)SDL_SetTextureScaleMode(texture,linear?SDL_SCALEMODE_LINEAR:SDL_SCALEMODE_NEAREST); + if(high.texture) (void)SDL_SetTextureScaleMode(high.texture,linear?SDL_SCALEMODE_LINEAR:SDL_SCALEMODE_NEAREST); + FreeHigh(candidate);(void)SDL_SetError("%s",saved);return DisplayError(); +} +static void RememberWindow(void) +{ + if(!window || pending || (SDL_GetWindowFlags(window)&(SDL_WINDOW_FULLSCREEN|SDL_WINDOW_MINIMIZED|SDL_WINDOW_MAXIMIZED))) return; + int w,h;if(SDL_GetWindowSize(window,&w,&h) && w>0 && h>0) { window_w=w;window_h=h; } +} +static bool WindowSize(int w,int h) { return !Fail(3) && SDL_SetWindowSize(window,w,h); } +static void RefreshDisplay(void) +{ + if(!window) return; + if(pending && Fullscreen()==target) { + if(!target && restore_size) { + restore_size=false; + if(!WindowSize(window_w,window_h)) { (void)DisplayError();pending=false; } + else size_pending=true; + } + int w=0,h=0; + if(size_pending && SDL_GetWindowSize(window,&w,&h) && w==window_w && h==window_h) size_pending=false; + if(!size_pending) { pending=false;IN_SDLDiscardInput(); } + } + if(pending && SDL_GetTicks()>=request_deadline) { + pending=size_pending=restore_size=false; + SDL_SetError("Window manager did not apply the display request");(void)DisplayError();IN_SDLDiscardInput(); + } + RememberWindow(); +} +bool VL_DisplayGet(display_settings *s) +{ + if(!window || !renderer || !s) return false; + RefreshDisplay();memset(s,0,sizeof(*s));s->fullscreen=Fullscreen();s->integer=integer_scale;s->pending=pending; + s->width=window_w;s->height=window_h; + s->high_resolution=high_resolution;s->render_width=render_width;s->render_height=render_height; + s->render_auto=render_auto;s->aspect=aspect;s->vsync=vsync;s->linear=linear;s->smooth=smooth; + for(unsigned i=1;i<=5;++i) if(window_w==(int)i*320 && window_h==(int)i*240) s->scale=i; + if(!SDL_GetRenderOutputSize(renderer,&s->pixel_width,&s->pixel_height)) return false; + (void)SDL_strlcpy(s->error,display_error,sizeof(s->error));return true; +} +bool VL_DisplayPreferences(display_settings *s) +{ + if(!VL_DisplayGet(s)) return false; + if(pending) s->fullscreen=target; + return true; +} +bool VL_DisplaySet(const display_settings *s) +{ + if(!window || !renderer || !s || s->scale>5 || (!s->scale && (s->width<1 || s->height<1 || s->width>16384 || s->height>16384))) return SDL_SetError("Invalid display settings"); + RefreshDisplay();if(pending) return SDL_SetError("Fullscreen request still pending"); + unsigned rw=s->render_width?s->render_width:640,rh=s->render_height?s->render_height:480; + if(!((rw==640 && rh==480) || (rw==1280 && rh==720) || (rw==1920 && rh==1080)) || s->aspect>5) + return SDL_SetError("Unsupported rendering resolution/aspect"); + unsigned actual_w=rw,actual_h=rh; + if(s->high_resolution && !RenderSize(s->render_auto,&actual_w,&actual_h)) return DisplayError(); + high_surface candidate={0}; + bool replace=s->high_resolution && (!high.texture || actual_w!=high.target.width || actual_h!=high.target.height); + if(replace && !CreateHigh(&candidate,actual_w,actual_h)) return DisplayError(); + if(s->vsync!=vsync && (Fail(7) || !SDL_SetRenderVSync(renderer,s->vsync?1:0))) { return SettingsFailure(&candidate); } + SDL_ScaleMode filter=s->linear?SDL_SCALEMODE_LINEAR:SDL_SCALEMODE_NEAREST; + if(Fail(8) || !SDL_SetTextureScaleMode(texture,filter) || + (high.texture && !SDL_SetTextureScaleMode(high.texture,filter)) || + (candidate.texture && !SDL_SetTextureScaleMode(candidate.texture,filter))) { + (void)SDL_SetRenderVSync(renderer,vsync?1:0); + (void)SDL_SetTextureScaleMode(texture,linear?SDL_SCALEMODE_LINEAR:SDL_SCALEMODE_NEAREST); + if(high.texture) (void)SDL_SetTextureScaleMode(high.texture,linear?SDL_SCALEMODE_LINEAR:SDL_SCALEMODE_NEAREST); + return SettingsFailure(&candidate); + } + RememberWindow();bool old_integer=integer_scale; + integer_scale=s->integer; + if(!ApplyPresentation()) { integer_scale=old_integer;return SettingsFailure(&candidate); } + int old_w=window_w,old_h=window_h; + if(s->scale) { window_w=(int)s->scale*320;window_h=(int)s->scale*240; } + else { window_w=s->width;window_h=s->height; } + if(s->fullscreen!=Fullscreen()) { + IN_SDLCapture(window,false,false);IN_SDLDiscardInput(); + bool denied=Fail(4); + if(Fail(1) || (!denied && ((s->fullscreen && !SDL_SetWindowFullscreenMode(window,NULL)) || !SDL_SetWindowFullscreen(window,s->fullscreen)))) { + window_w=old_w;window_h=old_h;integer_scale=old_integer; + char error[160];(void)SDL_strlcpy(error,SDL_GetError(),sizeof(error)); + (void)ApplyPresentation();(void)SDL_SetError("%s",error);return SettingsFailure(&candidate); + } + pending=true;target=s->fullscreen;restore_size=!target;request_deadline=SDL_GetTicks()+3000; + } else if(!Fullscreen() && (window_w!=old_w || window_h!=old_h)) { + if(!WindowSize(window_w,window_h)) { + window_w=old_w;window_h=old_h;integer_scale=old_integer; + char error[160];(void)SDL_strlcpy(error,SDL_GetError(),sizeof(error)); + (void)ApplyPresentation();(void)SDL_SetError("%s",error);return SettingsFailure(&candidate); + } + IN_SDLCapture(window,false,false);IN_SDLDiscardInput(); + pending=size_pending=true;target=false;request_deadline=SDL_GetTicks()+3000; + } + if(replace) { FreeHigh(&high);high=candidate; } + if(!s->high_resolution) FreeHigh(&high); + if(replace || high_resolution!=s->high_resolution || aspect!=s->aspect || render_auto!=s->render_auto || smooth!=s->smooth) high_uploaded=false; + high_resolution=s->high_resolution;render_width=rw;render_height=rh; + aspect=s->aspect;render_auto=s->render_auto;vsync=s->vsync;linear=s->linear;smooth=s->smooth;auto_retry=0; + display_error[0]=0;return true; +} +static bool Shortcut(const SDL_KeyboardEvent *key) +{ + unsigned code=(unsigned)key->scancode; + if(code>=SDL_SCANCODE_COUNT) return false; + if(consumed[code]) { if(key->type==SDL_EVENT_KEY_UP) consumed[code]=false;return true; } + if(key->type!=SDL_EVENT_KEY_DOWN || key->repeat || !IN_SDLFocused()) return false; + bool full=(code==SDL_SCANCODE_RETURN || code==SDL_SCANCODE_KP_ENTER) && (key->mod&SDL_KMOD_ALT); + if(!full && code!=SDL_SCANCODE_F11 && code!=SDL_SCANCODE_F12) return false; + if(code==SDL_SCANCODE_F12) { + consumed[code]=true; + if(!VL_Screenshot()) { (void)SDL_strlcpy(display_error,SDL_GetError(),sizeof(display_error));SDL_Log("Screenshot failed: %s",display_error); } + return true; + } + consumed[code]=true; + if(full) { + if(key->mod&SDL_KMOD_LALT) consumed[SDL_SCANCODE_LALT]=true; + if(key->mod&SDL_KMOD_RALT) consumed[SDL_SCANCODE_RALT]=true; + IN_SDLDiscardInput(); + } + display_settings s;if(!VL_DisplayGet(&s) || s.pending) return true; + if(full) s.fullscreen=!s.fullscreen;else s.integer=!s.integer; + (void)VL_DisplaySet(&s);return true; +} + +const char *VL_Error(void) { return SDL_GetError(); } + +void VL_Shutdown(void) +{ + IN_SDLFocusLost(); +#ifdef WOLF3D_DISPLAY_TEST + test_desktop_w=test_desktop_h=0;surface_creations=0; +#endif + present_ns=0;high_uploads=0;smooth=high_smooth=false;FreeHigh(&high);high_resolution=high_uploaded=render_auto=vsync=linear=false;aspect=0;high_scene=(wl_rectangle){0};render_width=640;render_height=480; + SDL_DestroyTexture(texture); texture = NULL; + SDL_DestroyRenderer(renderer); renderer = NULL; + SDL_DestroyWindow(window); window = NULL; + SDL_Quit(); + uploaded=false;integer_scale=pending=target=restore_size=size_pending=false; + window_w=960;window_h=720;applied_mode=SDL_LOGICAL_PRESENTATION_DISABLED; + display_error[0]=0;memset(consumed,0,sizeof(consumed));IN_SDLFocusLost(); +} + +bool VL_Startup(void) +{ + char error[512]; + VL_Shutdown(); + SDL_SetMainReady(); + if (!SDL_Init(SDL_INIT_VIDEO)) goto failed; + window = SDL_CreateWindow("Wolf3D Revive", 960, 720, SDL_WINDOW_RESIZABLE|SDL_WINDOW_HIGH_PIXEL_DENSITY); + if (!window) goto failed; + renderer = SDL_CreateRenderer(window, NULL); + if (!renderer) goto failed; + texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, + SDL_TEXTUREACCESS_STREAMING, W3R_SCREEN_WIDTH, W3R_SCREEN_HEIGHT); + if (!texture || !SDL_SetTextureScaleMode(texture, SDL_SCALEMODE_NEAREST) || + !ApplyPresentation()) goto failed; + IN_SDLReset();uploads = 0; + return true; +failed: + (void)SDL_strlcpy(error,SDL_GetError(),sizeof(error)); + VL_Shutdown(); + (void)SDL_SetError("%s",error); + return false; +} +static double RefreshRate(float current,float desktop) +{ + double rate=current; + if(!(rate>=1.0 && rate<=10000.0)) rate=desktop; + if(!(rate>=1.0 && rate<=10000.0)) rate=60.0; + return rate>240.0?240.0:rate; +} +#ifdef WOLF3D_DISPLAY_TEST +double VL_TestRefreshRate(float current,float desktop) { return RefreshRate(current,desktop); } +#endif +double VL_MonitorRefreshRate(void) +{ + if(!window) return 60.0; + SDL_DisplayID display=SDL_GetDisplayForWindow(window); + const SDL_DisplayMode *mode=SDL_GetCurrentDisplayMode(display); + float current=mode?mode->refresh_rate:0.0f; + if(current>=1.0f && current<=10000.0f) return RefreshRate(current,0.0f); + mode=SDL_GetDesktopDisplayMode(display); + return RefreshRate(current,mode?mode->refresh_rate:0.0f); +} +bool VL_VSyncPaced(double refresh) +{ + int interval=0; + return renderer && SDL_GetRenderVSync(renderer,&interval) && interval!=0 && + (double)present_ns>=500000000.0/refresh; +} +uint64_t VL_GetTicks70(void) { return TimeCount_FromNS(SDL_GetTicksNS()); } +void VL_Sleep(unsigned ms) { SDL_Delay(ms); } +uint64_t VL_TextureUploads(void) { return uploads; } + +static bool VL_DrawScreen(void) +{ + if (!renderer || !texture) return false; + bool changed=!uploaded || memcmp(last_frame,framebuffer,VL_PIXELS) || memcmp(last_palette,palette,768); + bool world=WorldPresentation(); + if(high_resolution && world) { + unsigned tw=render_width,th=render_height; + if(!RenderSize(render_auto,&tw,&th)) { (void)DisplayError();tw=high.target.width;th=high.target.height; } + if(!high.texture || high.target.width!=tw || high.target.height!=th) { + high_surface candidate; + if(SDL_GetTicks()=auto_retry) { (void)DisplayError();auto_retry=SDL_GetTicks()+1000; } + if(!high.texture) return false; + tw=high.target.width;th=high.target.height; + } else { FreeHigh(&high);high=candidate;high_uploaded=false;auto_retry=0; } + } + unsigned aw=4,ah=3; + static const unsigned ratios[][2]={{4,3},{4,3},{16,9},{16,10},{21,9},{32,9}}; + if(aspect) { aw=ratios[aspect][0];ah=ratios[aspect][1]; } + else { + int pw,ph;if(!SDL_GetRenderOutputSize(renderer,&pw,&ph) || pw<1 || ph<1) return false; + aw=(unsigned)pw;ah=(unsigned)ph; + if((uint64_t)aw*3<(uint64_t)ah*4) { aw=4;ah=3; } + if((uint64_t)aw*9>(uint64_t)ah*32) { aw=32;ah=9; } + } + wl_rectangle scene; + if(!WL_AspectFit(tw,th,aw,ah,&scene)) return SDL_SetError("Invalid aspect geometry"); + if(memcmp(&scene,&high_scene,sizeof(scene))) high_uploaded=false; + high_scene=scene; + } + if(!ApplyPresentation()) return false; + uint32_t death_cursor=0;unsigned death_phase=GameDeathPresentation(&death_cursor); + bool dying=world && gamestate.died; + bool interpolate=high_resolution && smooth && world && (GameCanSave() || Demo_Active() || (dying && death_phase==1)) && (!dying || death_phase==1) && !gamestate.victoryflag; + bool sampled=interpolate && WL_PresentSample(SDL_GetTicksNS(),&presentation); + if(high_resolution && world && (!high_uploaded || changed || world!=high_world || sampled || sampled!=high_smooth || dying!=high_dying || (dying && (death_phase!=high_death_phase || death_cursor!=high_death_cursor)) || (world && (high_time!=gamestate.TimeCount || high_serial!=WL_RenderSerial())))) { + if(!WL_RenderSnapshot(&high.target,high_depth,WL_TARGET_MAX_WIDTH,world,high_scene.width,high_scene.height,sampled?&presentation:NULL,Audio_Pump)) return SDL_SetError("High-resolution scene rendering failed"); + WL_PROFILE_BEGIN(convert_start); + /* Build words from RGBA bytes so the lookup is endian independent. + malloc gives the destination the alignment required for word stores. */ + uint32_t colors[256]; + for(unsigned i=0;i<256;++i) { + w3r_byte color[4]; + for(unsigned c=0;c<3;++c) { unsigned value=palette[i*3+c];color[c]=(w3r_byte)((value<<2)|(value>>4)); } + color[3]=255;memcpy(&colors[i],color,sizeof(color)); + } + for(unsigned y=0;y=sizeof(path)) { SDL_SetError("Screenshot path too long");break; } + SDL_PathInfo info; + if(SDL_GetPathInfo(path,&info)) continue; + ok=VL_Capture(path);break; + } + SDL_free(dir);return ok; +} diff --git a/src/platform/sdl_video.h b/src/platform/sdl_video.h new file mode 100644 index 00000000..66d04d49 --- /dev/null +++ b/src/platform/sdl_video.h @@ -0,0 +1,36 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef SDL_VIDEO_H +#define SDL_VIDEO_H +#include +#include +#include "display_settings.h" + +bool VL_Startup(void); +bool VL_DisplayGet(display_settings *settings); +bool VL_DisplayPreferences(display_settings *settings); /* Pending accepted intent for persistence. */ +bool VL_DisplaySet(const display_settings *settings); +#ifdef WOLF3D_DISPLAY_TEST +/* One-shot fault injection, compiled only into the display test executable. */ +uint64_t VL_TestSceneUploads(void); +void VL_TestDesktopSize(unsigned width,unsigned height); +uint64_t VL_TestSurfaceCreations(void); +struct SDL_Texture *VL_TestSceneTexture(void); +void VL_TestDisplayFailure(unsigned operation); /* 1 fullscreen, 2 scaling, 3 size, 4 denied request, 5 allocation, 6 texture, 7 VSync, 8 filter */ +void VL_TestExpireDisplayRequest(void); +#endif +uint64_t VL_GetTicks70(void); +double VL_MonitorRefreshRate(void); /* Current output Hz, bounded, 60 Hz fallback. */ +bool VL_VSyncPaced(double refresh); /* Last present actually blocked for VSync. */ +#ifdef WOLF3D_DISPLAY_TEST +double VL_TestRefreshRate(float current,float desktop); +#endif +void VL_Sleep(unsigned ms); +uint64_t VL_TextureUploads(void); +void VL_Shutdown(void); +bool VW_UpdateScreen(void); +bool VL_PollQuit(void); +/* Diagnostic capture of the rendered viewport; game artwork stays local. */ +bool VL_Screenshot(void); +bool VL_Capture(const char *path); +const char *VL_Error(void); +#endif diff --git a/src/w3r_types.h b/src/w3r_types.h new file mode 100644 index 00000000..e59a60ff --- /dev/null +++ b/src/w3r_types.h @@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Portable type baseline. Original DOS headers remain untouched. */ +#ifndef W3R_TYPES_H +#define W3R_TYPES_H + +#include +#include + +typedef uint8_t w3r_byte; +typedef uint16_t w3r_word; +typedef uint32_t w3r_longword; +typedef int32_t w3r_fixed; + +_Static_assert(CHAR_BIT == 8, "Wolf3D data requires 8-bit bytes"); +_Static_assert(sizeof(w3r_word) == 2, "Wolf3D words must be 16-bit"); +_Static_assert(sizeof(w3r_longword) == 4, "Wolf3D longwords must be 32-bit"); +_Static_assert(sizeof(w3r_fixed) == 4, "Wolf3D fixed-point values must be 32-bit"); + +enum { W3R_SCREEN_WIDTH = 320, W3R_SCREEN_HEIGHT = 200, W3R_TICK_HZ = 70 }; + +#endif diff --git a/tests/aspect_tests.c b/tests/aspect_tests.c new file mode 100644 index 00000000..e755bb7b --- /dev/null +++ b/tests/aspect_tests.c @@ -0,0 +1,46 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_ASPECT.h" +#include +#include +#include +#include +#include +#include +int main(void) +{ + wl_rectangle r={0};double f=0; + assert(WL_AspectFit(1920,1080,4,3,&r)); + assert(r.width==1440 && r.height==1080 && r.x==240 && r.y==0); + assert(WL_AspectFit(1280,720,16,9,&r)); + assert(r.width==1280 && r.height==720 && r.x==0 && r.y==0); + assert(WL_AspectFit(800,600,16,9,&r)); + assert(r.width==800 && r.height==450 && r.y==75); + assert(!WL_AspectFit(0,1080,4,3,&r)); + assert(!WL_AspectFit(1920,1080,0,3,&r)); + assert(WL_HorizontalFov(60,4,3,&f)&&fabs(f-60)<0.000001); + assert(WL_HorizontalFov(60,16,9,&f)&&f>60); + assert(WL_HorizontalFov(60,21,9,&f)&&f>70); + assert(!WL_HorizontalFov(0,16,9,&f)); + wl_rectangle old=r; + assert(!WL_AspectFit(1,1,UINT_MAX,1,&r));assert(!memcmp(&r,&old,sizeof(r))); + assert(WL_AspectFit(UINT_MAX,UINT_MAX,UINT_MAX,UINT_MAX,&r));assert(r.width==UINT_MAX && r.height==UINT_MAX); + assert(!WL_HorizontalFov(NAN,4,3,&f));assert(!WL_HorizontalFov(INFINITY,4,3,&f)); + assert(!WL_HorizontalFov(DBL_TRUE_MIN,1,UINT_MAX,&f)); + assert(!WL_HorizontalFov(60,0,9,&f));assert(!WL_HorizontalFov(60,4,3,NULL)); + assert(WL_HorizontalFov(60,16,10,&f) && f>60);assert(WL_HorizontalFov(60,32,9,&f) && f>110 && f<120); + unsigned w=0,h=0; + assert(WL_AutoRenderSize(3840,2160,&w,&h) && w==1920 && h==1080); + assert(WL_AutoRenderSize(2560,1440,&w,&h) && w==1920 && h==1080); + assert(WL_AutoRenderSize(1920,1080,&w,&h) && w==1920 && h==1080); + assert(WL_AutoRenderSize(1280,720,&w,&h) && w==1280 && h==720); + assert(WL_AutoRenderSize(1600,1200,&w,&h) && w==1440 && h==1080); + assert(WL_AutoRenderSize(3840,1080,&w,&h) && w==1920 && h==540); + assert(WL_AutoRenderSize(3440,1440,&w,&h) && w==1920 && h>=803 && h<=804); + assert(WL_AutoRenderSize(1080,1920,&w,&h) && w==607 && h==1080); + assert(WL_AutoRenderSize(UINT_MAX,UINT_MAX,&w,&h) && w==1080 && h==1080); + unsigned old_w=w,old_h=h; + assert(!WL_AutoRenderSize(UINT_MAX,200,&w,&h) && w==old_w && h==old_h); + assert(!WL_AutoRenderSize(100,100,&w,&h) && w==old_w && h==old_h); + assert(!WL_AutoRenderSize(3840,2160,NULL,&h)); + return 0; +} diff --git a/tests/audio_fixtures.py b/tests/audio_fixtures.py new file mode 100644 index 00000000..ca8c1958 --- /dev/null +++ b/tests/audio_fixtures.py @@ -0,0 +1,51 @@ +"""Invented audio bytes only. No commercial samples or music fixtures.""" +import struct + +def audio_files(path): + sounds = [] + for i in range(87): + sounds.append(struct.pack('= 6 and 6 + 6 * struct.unpack_from(" +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s; %s)\n",__LINE__,#x,CA_Error(),Audio_Error());exit(1); } } while(0) +static int16_t pcm[48000*2],other[48000*2]; +static void Reset(unsigned rate) +{ + SD_SetEnabled(true,true);SD_SetVolumes(70,85);SD_SetDigitizedMode(true); + CHECK(SD_Startup(rate)); +} +static long long Energy(const int16_t *p,size_t frames,unsigned channel) +{ + long long sum=0;for(size_t i=0;i12 && Energy(pcm,rate,0)>10000); + uint64_t writes=s.writes;SD_Render(other,1);SD_GetStatus(&s); + CHECK(s.ticks==701 && s.loops==1 && s.writes==writes+12 && s.registers[0xb1]==0x31); + /* One large request and arbitrarily split requests must be identical. */ + Reset(rate);SD_StartMusic(0);SD_Render(other,1);SD_Render(other+2,17);SD_Render(other+36,rate-18); + CHECK(!memcmp(pcm,other,rate*2*sizeof(*pcm))); + SD_StartMusic(-1);SD_GetStatus(&s);CHECK(s.registers[0xb1]==0 && s.music==-1); + } +} +static void PauseMusic(void) +{ + Reset(48000);SD_StartMusic(0);SD_Render(pcm,24000); + SD_SetMusicPaused(true);CHECK(SD_MusicPaused()); + unsigned m,e;bool mon,eon;SD_GetSettings(&m,&e,&mon,&eon);CHECK(mon && eon && m==70 && e==85); + sd_status before,after;SD_GetStatus(&before);SD_Render(pcm,48000);SD_GetStatus(&after); + CHECK(after.loops==before.loops && after.music==before.music && after.writes==before.writes); + SD_SetMusicPaused(false);SD_Render(pcm,24000);SD_GetStatus(&after); + CHECK(!SD_MusicPaused() && after.loops==1); /* Resumes halfway; does not restart. */ + SD_SetMusicPaused(true);SD_StartMusic(1);CHECK(!SD_MusicPaused()); +} +static void Effects(void) +{ + Reset(48000);SD_SetDigitizedMode(false);SD_StartMusic(0); + CHECK(SD_PlaySound(MISSILEHITSND,0,0));CHECK(!SD_PlaySound(HITWALLSND,0,0)); + CHECK(SD_PlaySound(MISSILEHITSND,0,0)); /* Equal priority interrupts. */ + SD_Render(pcm,48000);sd_status s;SD_GetStatus(&s); + CHECK(s.sound==-1 && !s.sound_priority && s.registers[0xb0]==0); + CHECK(s.loops==1 && Energy(pcm,48000,0)>10000); + Reset(48000);CHECK(SD_PlaySound(MISSILEHITSND,0,0));SD_Render(pcm,4800); + SD_GetStatus(&s);CHECK(s.registers[0xb0]==0x30 && s.registers[0xc0]==0); + /* One chip: effect channel zero and IMF channel one coexist. */ + SD_StartMusic(0);SD_Render(pcm,480);SD_GetStatus(&s); + CHECK(s.registers[0xb0]==0x30 && s.registers[0xb1]==0x31); + SD_SetDigitizedMode(true);CHECK(SD_PlaySound(ROSESND,0,15)); + CHECK(!SD_PlaySound(HALTSND,0,0));SD_GetStatus(&s); + CHECK(s.digitized==45 && s.digi_priority==85 && s.sound_priority==87); + SD_StopSound();CHECK(!SD_PlaySound((soundnames)LASTSOUND,0,0)); + Reset(48000);SD_SetDigitizedMode(false);CHECK(SD_PlaySound(MISSILEHITSND,0,0)); + SD_StartMusic(26);SD_Render(pcm,276);SD_GetStatus(&s); + /* At tick 4 the effect writes first; IMF overwrites the SAME chip channel. */ + CHECK(s.registers[0xb0]==0x2c && s.registers[0xa0]==37); + /* Exact SB time constant: 142 source samples last 142*142 microseconds. */ + Reset(48000);CHECK(SD_PlaySound(HALTSND,0,15));SD_Render(pcm,968); + CHECK(Energy(pcm,968,0)>100000 && !Energy(pcm,968,1)); + SD_GetStatus(&s);CHECK(s.digitized==0);SD_Render(pcm,1);SD_GetStatus(&s);CHECK(s.digitized==-1); + CHECK(SD_PlaySound(DEATHSCREAM2SND,0,0));SD_GetStatus(&s);CHECK(s.digitized==13); + CHECK(SD_PlaySound(DEATHSCREAM3SND,0,0));SD_GetStatus(&s);CHECK(s.digitized==13); +} +static void Volume(void) +{ + Reset(48000);SD_StartMusic(0);SD_SetVolumes(0,0);SD_Render(pcm,48000); + CHECK(!Energy(pcm,48000,0) && !Energy(pcm,48000,1)); + SD_SetVolumes(100,100);SD_StartMusic(0);SD_Render(pcm,48000);CHECK(Energy(pcm,48000,0)>10000); + /* The invented single-channel IMF tone must reach a useful PCM level; + this catches a return to the OPL core's quiet, uncalibrated output. */ + int peak=0;for(size_t i=0;i<48000*2;++i) if(abs(pcm[i])>peak) peak=abs(pcm[i]); + CHECK(peak>=7000 && peak<=9000); + SD_SetEnabled(false,false);SD_Render(pcm,48000);SD_Render(pcm,48000); + CHECK(!Energy(pcm,48000,0) && !SD_PlaySound(HALTSND,0,0)); + SD_SetEnabled(true,true);SD_SetVolumes(0,50);SD_StopSound(); + CHECK(SD_PlaySound(HALTSND,0,0));SD_Render(pcm,968);long long half=Energy(pcm,968,0); + SD_SetVolumes(0,100);CHECK(SD_PlaySound(HALTSND,0,0));SD_Render(pcm,968); + CHECK(Energy(pcm,968,0)==2*half); +} +static void PositionAndRNG(void) +{ + BuildTables();player.x=player.y=20*TILEGLOBAL;player.angle=0; + unsigned l,r;GameSoundPosition(player.x,player.y,&l,&r);CHECK(!l && !r); + GameSoundPosition(player.x,player.y+4*TILEGLOBAL,&l,&r);CHECK(l>r); + GameSoundPosition(player.x,player.y-4*TILEGLOBAL,&l,&r);CHECK(r>l); + player.angle=180;GameSoundPosition(player.x,player.y+4*TILEGLOBAL,&l,&r);CHECK(r>l); + GameSoundPosition(0,0,&l,&r);CHECK(l==8 && r==8); + US_InitRndT(20);int expected=US_RndT();US_InitRndT(20); + Reset(48000);SD_StartMusic(0);GameSound(HALTSND,&player);SD_Render(pcm,48000);CHECK(US_RndT()==expected); + SD_SetDigitizedMode(true);SD_SetEnabled(false,false);CHECK(SD_DigitizedMode());SD_Shutdown();CHECK(SD_DigitizedMode()); +} +static void OwnedTracks(void) +{ + memptr head=NULL,archive=NULL;size_t hs,as; + CHECK(CA_ReadDataFile("AUDIOHED.WL6",&head,&hs));CHECK(CA_ReadDataFile("AUDIOT.WL6",&archive,&as)); + CHECK(hs>=289*4); + for(unsigned song=0;song<27;++song) { + const uint8_t *s=(const uint8_t *)archive+CA_LE32((const uint8_t *)head+(261+song)*4); + size_t length=CA_LE16(s);uint64_t ticks=0; + for(size_t pos=0;pos+448000?48000:remaining);SD_Render(pcm,frames);remaining-=frames; + /* Full-volume FM must retain headroom through every owned loop. */ + for(size_t i=0;i0 && s.writes>0); + Audio_Shutdown();Audio_Shutdown();CHECK(!Audio_Active() && !SD_Ready()); + } + (void)SDL_setenv_unsafe("SDL_AUDIODRIVER","nonexistent-wolf-test",1); + CHECK(!Audio_Startup());CHECK(!Audio_Active() && !SD_Ready() && *Audio_Error());Audio_Shutdown(); +} +int main(int argc,char **argv) +{ + CHECK(argc>=2);MM_Startup(); + if(!CA_Startup(argv[1])) { + CHECK(argc==3 && !strcmp(argv[2],"invalid")); + CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes());return 0; + } + if(argc==3 && !strcmp(argv[2],"invalid")) { + CHECK(!SD_Startup(48000));CHECK(!SD_Ready());SD_Shutdown(); + } else if(argc==3 && !strcmp(argv[2],"listen")) Device(true); + else if(argc==3 && !strcmp(argv[2],"gameplay")) GameplayIndependence(); + else if(argc==3 && !strcmp(argv[2],"owned")) { + OwnedTracks();Reset(48000); + for(int song=0;song<27;++song) { SD_StartMusic(song);SD_Render(pcm,48000);CHECK(Energy(pcm,48000,0)>0); } + for(unsigned sound=0;sound +#include +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%d: %s (%s; %s)\n",__LINE__,#x,CA_Error(),VL_Error());exit(1); } } while (0) +static uint64_t ticks; +static unsigned shots; +static void Sound(soundnames sound,const objtype *ob) +{ + (void)ob;if (sound==NAZIFIRESND || sound==BOSSFIRESND) ++shots; +} +static void Step(void) +{ + CHECK(!VL_PollQuit());CHECK(GameStep(++ticks));CHECK(VW_UpdateScreen()); +} +static void Capture(const char *name) +{ + const char *dir=getenv("WOLF3D_CAPTURE_DIR");if (!dir) return; + char path[1024];int n=snprintf(path,sizeof(path),"%s/%s.bmp",dir,name); + CHECK(n>0 && (size_t)ntilex+dx,y=ob->tiley+dy; + if (x<1 || y<1 || x>62 || y>62) continue; + player.x=x*TILEGLOBAL+32768;player.y=y*TILEGLOBAL+32768; + player.tilex=x;player.tiley=y; + double angle=atan2((double)player.y-ob->y,(double)ob->x-player.x); + if (angle<0) angle+=6.28318530717958647692; + player.angle=(int)(angle*360/6.28318530717958647692); + ConnectAreas(); + if (TryMove(&player) && CheckLine(ob)) placed=true; + } + CHECK(placed);CHECK(ThreeDRefresh() && DrawStatus() && VW_UpdateScreen()); +} +int main(int argc,char **argv) +{ + CHECK(argc==2 || argc==3);MM_Startup();CHECK(CA_Startup(argv[1]));CHECK(VL_Startup()); + CHECK(VL_SetPalette(gamepal,768));SetGameSoundHook(Sound); + bool owned=argc==3; + CHECK(GameStartSelected(0,owned ? 1U : 0U,2)); + if (owned) { ShutdownGameLevel();gamestate.mapon=7;CHECK(SetupGameLevel()); } + objtype *boss=Find(bossobj); + /* E2M8 Hans encounters start in enclosed rooms. Open nearby real doors + through the existing door API before arranging this controlled shot. */ + if (owned) { + for (unsigned i=0;itilex)<10 && + abs((int)doorobjlist[i].y-boss->tiley)<10) OpenDoor(i); + for (unsigned tic=0;tic<70;++tic) MoveDoors(); + } + FaceActor(boss);Capture("boss-standing"); + /* Deliver a real SDL key edge to the existing weapon simulation. */ + int hp=boss->hitpoints;SDL_Event event={0}; + event.type=SDL_EVENT_KEY_DOWN;event.key.scancode=SDL_SCANCODE_LCTRL;CHECK(SDL_PushEvent(&event)); + Step(); + event.type=SDL_EVENT_KEY_UP;CHECK(SDL_PushEvent(&event)); + for (unsigned i=0;i<55;++i) { gamestate.health=100;Step(); } + CHECK(boss->hitpointsx,y=ghost->y; + for (unsigned i=0;i<70;++i) { gamestate.health=100;Step(); } + CHECK(ghost->x!=x || ghost->y!=y);Capture("ghost-moving"); + SetGameSoundHook(NULL);GameStop();VL_Shutdown();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); + puts("SDL input damages a boss; boss fires; ghosts render and chase with owned or synthetic data."); + return 0; +} diff --git a/tests/boss_tests.c b/tests/boss_tests.c new file mode 100644 index 00000000..dd7a8079 --- /dev/null +++ b/tests/boss_tests.c @@ -0,0 +1,168 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_DEF.h" +#include "engine/ID_CA.h" +#include "engine/ID_US_1.h" +#include "engine/ID_VL.h" +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%d: %s (%s)\n",__LINE__,#x,CA_Error());exit(1); } } while (0) +extern statetype s_bossstand,s_bosschase1,s_bossshoot1,s_bossdie1,s_bossdie4; +extern statetype s_gretelstand,s_gretelchase1,s_gretelshoot1,s_greteldie1,s_greteldie4; +static unsigned sounds,shots; +static soundnames lastsound; +static const objtype *lastsource; +static void Sound(soundnames sound,const objtype *source) +{ + ++sounds;lastsound=sound;lastsource=source; + if (sound==BOSSFIRESND || sound==NAZIFIRESND) ++shots; +} +static void PlacePlayer(int x,int y) +{ + player.x=x*TILEGLOBAL+32768;player.y=y*TILEGLOBAL+32768; + player.tilex=x;player.tiley=y;player.angle=0;ConnectAreas(); +} +static void Start(unsigned diff) +{ + CHECK(NewGame(diff,0));US_InitRndT(0);CHECK(SetupGameLevel()); + CHECK(objcount==6 && gamestate.killtotal==6); + sounds=shots=0; +} +static void TestSpawns(void) +{ + static const int hp[]={850,950,1050,1200}; + static const int sprites[]={SPR_BLINKY_W1,SPR_CLYDE_W1,SPR_PINKY_W1,SPR_INKY_W1}; + for (unsigned diff=0;diff<4;++diff) { + Start(diff); + CHECK(objlist[0].state==&s_bossstand && objlist[0].obclass==bossobj); + CHECK(objlist[1].state==&s_gretelstand && objlist[1].obclass==gretelobj); + for (unsigned i=0;i<2;++i) { + CHECK(objlist[i].hitpoints==hp[diff] && objlist[i].speed==SPDPATROL); + CHECK(objlist[i].flags==(FL_SHOOTABLE|FL_AMBUSH)); + CHECK(objlist[i].dir==(i ? north : south) && !objlist[i].ticcount); + } + for (unsigned i=0;i<4;++i) { + objtype *ghost=&objlist[i+2]; + CHECK(ghost->obclass==ghostobj && ghost->state->shapenum==sprites[i]); + CHECK(ghost->dir==east && ghost->speed==SPDDOG && ghost->flags==FL_AMBUSH); + CHECK(!ghost->hitpoints && actorat[ghost->tilex][ghost->tiley]==ghost); + DamageActor(ghost,10000);CHECK(!gamestate.killcount && ghost->flags==FL_AMBUSH); + } + /* Stand states draw no RNG; four ghost states draw once each. */ + CHECK(US_RndT()==241); + ShutdownGameLevel(); + } +} +static void TestBoss(unsigned which) +{ + Start(2);objtype *ob=&objlist[which]; + statetype *chase=which ? &s_gretelchase1 : &s_bosschase1; + statetype *shoot=which ? &s_gretelshoot1 : &s_bossshoot1; + statetype *die=which ? &s_greteldie1 : &s_bossdie1; + statetype *dead=which ? &s_greteldie4 : &s_bossdie4; + /* Ambush wakeup requires sight; hearing alone cannot wake a boss. */ + madenoise=true;tilemap[ob->tilex][ob->tiley+1]=1; + PlacePlayer(ob->tilex,ob->tiley+2); + CHECK(!SightPlayer(ob) && !ob->temp2 && (ob->flags&FL_AMBUSH)); + tilemap[ob->tilex][ob->tiley+1]=0; + PlacePlayer(ob->tilex,ob->tiley+(which ? -2 : 2)); + US_InitRndT(0);CHECK(!SightPlayer(ob) && ob->temp2==1); + CHECK(SightPlayer(ob) && ob->state==chase && ob->speed==1536); + CHECK(lastsound==(which ? KEINSND : GUTENTAGSND) && !lastsource); + CHECK(!(ob->flags&FL_AMBUSH) && (ob->flags&FL_ATTACKMODE)); + CHECK(US_RndT()==8); /* No sight-sound RNG. */ + /* Close-range original chase probability always starts the burst. */ + PlacePlayer(ob->tilex+1,ob->tiley);ob->distance=0;ob->dir=nodir; + T_Chase(ob);CHECK(ob->state==shoot && ob->ticcount==30); + ob->speed=0;shots=0; + for (unsigned tic=1;tic<=99;++tic) { + gamestate.health=100;gamestate.died=false; + DoActor(ob); + CHECK(shots==(tic<40 ? 0U : tic>=90 ? 6U : (tic-30)/10)); + CHECK(ob->state!=chase); + } + gamestate.victoryflag=true;DoActor(ob);CHECK(ob->state==chase && shots==6); + gamestate.victoryflag=false; + /* Distant Hans shots use dist*2/3; Gretel retains normal accuracy. */ + PlacePlayer(ob->tilex+6,ob->tiley);ob->flags|=FL_VISABLE; + gamestate.health=100;US_InitRndT(0);T_Shoot(ob); + CHECK(gamestate.health==94 && lastsource==ob); + gamestate.health=100;US_InitRndT(23);T_Shoot(ob); + CHECK(gamestate.health==(which ? 100 : 95)); + CHECK(US_RndT()==(which ? 89 : 77)); + /* Kill and key drop happen immediately; corpse animation lasts 45 tics. */ + int score=gamestate.score;DamageActor(ob,10000); + CHECK(ob->state==die && gamestate.score==score+5000 && gamestate.killcount==1); + CHECK(!(ob->flags&FL_SHOOTABLE) && (ob->flags&FL_NONMARK)); + CHECK(!actorat[ob->tilex][ob->tiley]); + CHECK(statcount==1 && statobjlist[0].itemnumber==bo_key1); + CHECK(statobjlist[0].tilex==ob->tilex && statobjlist[0].tiley==ob->tiley); + unsigned before=sounds; + for (unsigned tic=0;tic<45;++tic) DoActor(ob); + CHECK(ob->state==dead && !ob->ticcount && sounds==before+1); + CHECK(lastsound==(which ? MEINSND : MUTTISND) && !lastsource); + CHECK(!gamestate.victoryflag && playstate==ex_playing); + for (unsigned tic=0;tic<100;++tic) DoActor(ob); + CHECK(ob->state==dead && gamestate.killcount==1 && statcount==1); + PlacePlayer(ob->tilex,ob->tiley);GetBonus(&statobjlist[0]);CHECK(gamestate.keys==1); + ShutdownGameLevel(); +} +static void TestGhosts(void) +{ + Start(2); + for (unsigned i=2;i<6;++i) { + objtype *ob=&objlist[i];PlacePlayer(2,2); + statetype *first=ob->state;ob->speed=0;ob->ticcount=10; + for (unsigned tic=0;tic<9;++tic) DoActor(ob); + CHECK(ob->state==first); + DoActor(ob);CHECK(ob->state==first->next && ob->ticcount==10); + for (unsigned tic=0;tic<10;++tic) DoActor(ob); + CHECK(ob->state==first && ob->ticcount==10); + ob->speed=SPDDOG; + PlacePlayer(ob->tilex+1,ob->tiley); + int32_t x=ob->x;int health=gamestate.health; + ob->dir=east;ob->distance=TILEGLOBAL;MoveObj(ob,SPDDOG); + CHECK(gamestate.health==health-2 && ob->x==x && ob->distance==TILEGLOBAL); + PlacePlayer(2,2);MoveObj(ob,SPDDOG); + CHECK(ob->x==x+SPDDOG && ob->distance==TILEGLOBAL-SPDDOG); + /* Walls and shootable reservations block ghosts. Other ghosts do not. */ + ob->dir=east;tilemap[ob->tilex+1][ob->tiley]=1;CHECK(!TryWalk(ob)); + tilemap[ob->tilex+1][ob->tiley]=0; + actorat[ob->tilex+1][ob->tiley]=&objlist[0];CHECK(!TryWalk(ob)); + actorat[ob->tilex+1][ob->tiley]=&objlist[2];CHECK(TryWalk(ob)); + } + /* Closed-door wait must not turn the negative distance into a huge move. */ + objtype *ob=&objlist[2];ob->distance=-1;ob->dir=east; + int32_t x=ob->x;T_Ghosts(ob); + CHECK(ob->x==x && ob->distance==-1 && doorobjlist[0].action==dr_opening); + doorobjlist[0].action=dr_open;T_Ghosts(ob); + CHECK(ob->x==x+SPDDOG && ob->distance==TILEGLOBAL-SPDDOG); + ShutdownGameLevel(); +} +static void TestDeathSoundRNG(void) +{ + objtype ob={.obclass=guardobj}; + gamestate.episode=0;gamestate.mapon=0;US_InitRndT(0);A_DeathScream(&ob); + CHECK(lastsound==DEATHSCREAM1SND && US_RndT()==109); + gamestate.mapon=9;US_InitRndT(0);A_DeathScream(&ob); + CHECK(lastsound==DEATHSCREAM7SND && US_RndT()==220); + /* The rare draw returns before normal sound selection. */ + US_InitRndT(255);A_DeathScream(&ob);CHECK(lastsound==DEATHSCREAM6SND && US_RndT()==8); + ob.obclass=bossobj;US_InitRndT(255);A_DeathScream(&ob); + CHECK(lastsound==MUTTISND && US_RndT()==8); + /* It is absolute map index nine, not every episode's secret floor. */ + gamestate.episode=1;US_InitRndT(0);A_DeathScream(&ob);CHECK(US_RndT()==8); + ob.obclass=officerobj;gamestate.episode=0; + US_InitRndT(0);A_DeathScream(&ob);CHECK(lastsound==NEINSOVASSND && US_RndT()==109); + /* A disconnected sound sink must still consume the same draws. */ + SetGameSoundHook(NULL);ob.obclass=guardobj; + US_InitRndT(0);A_DeathScream(&ob);CHECK(US_RndT()==220); + SetGameSoundHook(Sound); +} +int main(int argc,char **argv) +{ + CHECK(argc==2);MM_Startup();CHECK(CA_Startup(argv[1]));CHECK(VL_SetPalette(gamepal,768)); + SetGameSoundHook(Sound); + TestSpawns();TestBoss(0);TestBoss(1);TestGhosts();TestDeathSoundRNG(); + SetGameSoundHook(NULL);GameStop();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); + puts("Hans, Gretel, ghosts, sound events and original death RNG passed.");return 0; +} diff --git a/tests/campaign_sdl_tests.c b/tests/campaign_sdl_tests.c new file mode 100644 index 00000000..7bd7515d --- /dev/null +++ b/tests/campaign_sdl_tests.c @@ -0,0 +1,87 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_DEF.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_MENU.h" +#include "engine/ID_CA.h" +#include "platform/sdl_video.h" +#include +#include +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%d: %s (%s; %s)\n",__LINE__,#x,CA_Error(),VL_Error());exit(1); } } while (0) +#include "finish_loading.h" +static uint64_t ticks; +static void Step(unsigned delta) { ticks+=delta;CHECK(!VL_PollQuit());CHECK(DemoLoop(ticks));if(GameLoading()) TestFinishLoading(ticks);CHECK(VW_UpdateScreen()); } +static void Tap(SDL_Scancode scan) +{ + SDL_Event e;memset(&e,0,sizeof(e));e.key.scancode=scan; + e.type=SDL_EVENT_KEY_DOWN;CHECK(SDL_PushEvent(&e)); + e.type=SDL_EVENT_KEY_UP;CHECK(SDL_PushEvent(&e));Step(1); +} +static void Capture(int argc,char **argv,const char *name) +{ + if (argc<3 || strcmp(argv[2],"--missing-next")==0) return; + char path[1024];int n=snprintf(path,sizeof(path),"%s/%s.bmp",argv[2],name); + CHECK(n>0 && (size_t)nnumber==10); + Capture(argc,argv,"episode2-hard"); + Tap(SDL_SCANCODE_ESCAPE);Step(21);CHECK(DemoLoopState()==UI_MENU); + /* Start the default E1M1 independently of the last selected menu choice. */ + CHECK(DemoLoopStartGame(ticks));Step(11);CHECK(gamestate.episode==0 && gamestate.difficulty==2); + bool pushed=false; + static const int dx[]={1,0,-1,0},dy[]={0,-1,0,1}; + for (int y=2;y<62 && !pushed;++y) for (int x=2;x<62 && !pushed;++x) { + if (!pushable[x][y]) continue; + for (unsigned d=0;d<4;++d) { + int px0=x-dx[d],py0=y-dy[d]; + if (tilemap[px0][py0] || tilemap[x+dx[d]][y+dy[d]] || + staticblock[x+dx[d]][y+dy[d]] || actorat[x+dx[d]][y+dy[d]]) continue; + player.tilex=px0;player.tiley=py0;player.x=px0*TILEGLOBAL+32768; + player.y=py0*TILEGLOBAL+32768;player.angle=(int)d*90; + if (!TryMove(&player)) continue; + CHECK(ThreeDRefresh() && VW_UpdateScreen());Capture(argc,argv,"pushwall-before"); + Tap(SDL_SCANCODE_SPACE);CHECK(pwallstate==1 && gamestate.secretcount==1); + for (unsigned t=0;t<63;++t) Step(1); + CHECK(pwallstate==64 && pwallpos==32);Capture(argc,argv,"pushwall-moving"); + for (unsigned t=0;t<192;++t) Step(1); + CHECK(!pwallstate && !pushable[x][y]);pushed=true;break; + } + } + CHECK(pushed);Capture(argc,argv,"pushwall-open"); + CHECK(DemoLoopStartGame(ticks));Step(11); + /* Synthetic campaign has the normal switch at 4,2. For owned captures, + locate a real elevator and use its actual neighbouring floor instead. */ + int ex=-1,ey=-1,px=0; + for (int y=1;y<63 && ex<0;++y) for (int x=1;x<63;++x) if (tilemap[x][y]==21) { + if (!tilemap[x-1][y]) { ex=x;ey=y;px=x-1;break; } + if (!tilemap[x+1][y]) { ex=x;ey=y;px=x+1;break; } + } + CHECK(ex>=0);player.tilex=px;player.tiley=ey;player.x=px*TILEGLOBAL+32768; + player.y=ey*TILEGLOBAL+32768;player.angle=pxnumber==1 && gamestate.oldscore==score); + Capture(argc,argv,"floor2"); + GameStop();VL_Shutdown();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); + puts("SDL episode/difficulty selection, cancellation, elevator, intermission and next floor passed.");return 0; +} diff --git a/tests/campaign_tests.c b/tests/campaign_tests.c new file mode 100644 index 00000000..1b6bb9b4 --- /dev/null +++ b/tests/campaign_tests.c @@ -0,0 +1,150 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_DEF.h" +#include "engine/ID_CA.h" +#include "engine/ID_IN.h" +#include "engine/ID_PM.h" +#include "engine/ID_VL.h" +#include "engine/WL_MAIN.h" +#include +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%d: %s (%s)\n",__LINE__,#x,CA_Error());exit(1); } } while (0) +static void Key(unsigned scan) { IN_KeyEvent(scan,true);IN_KeyEvent(scan,false); } +static void Place(int x,int y,int angle) +{ + player.x=x*TILEGLOBAL+32768;player.y=y*TILEGLOBAL+32768; + player.tilex=x;player.tiley=y;player.angle=angle; +} +static void TestDifficulty(void) +{ + CHECK(!NewGame(4,0) && !NewGame(2,6)); + for (unsigned ep=0;ep<6;++ep) for (unsigned diff=0;diff<4;++diff) { + CHECK(GameStartSelected(0,ep,diff)); + unsigned count=diff<2 ? 2 : diff==2 ? 4 : 6; + CHECK(CA_Map()->number==ep*10 && objcount==count && gamestate.killtotal==(int)count); + CHECK(gamestate.episode==(int)ep && gamestate.difficulty==(int)diff); + for (unsigned i=0;inumber==1 && gamestate.mapon==1); + CHECK(gamestate.health==37 && gamestate.ammo==48 && gamestate.weapon==wp_chaingun && gamestate.bestweapon==wp_chaingun); + CHECK(gamestate.oldscore==score && !gamestate.TimeCount && !gamestate.keys); + CHECK(doorobjlist[0].action==dr_closed && !doorobjlist[0].position); + /* Die on a later floor: return to that floor, restore its entry score. */ + GivePoints(100);TakeDamage(100,NULL); + while (gamestate.died && t<500) CHECK(GameStep(++t)); + CHECK(!gamestate.died && CA_Map()->number==1 && gamestate.score==score && gamestate.lives==lives-1); + CHECK(gamestate.health==100 && gamestate.ammo==8 && gamestate.weapon==wp_pistol && !gamestate.keys); + /* Secret elevator raw area marker, then the original episode return. */ + Place(3,2,0);((maptype *)CA_Map())->planes[0][2*64+3]=107; + Key(sc_Space);CHECK(GameStep(++t) && GameIntermission() && playstate==ex_secretlevel); + Key(sc_Enter);CHECK(GameStep(++t) && GameIntermission() && !LevelIntermissionCounting()); + Key(sc_Enter);CHECK(GameStep(++t) && CA_Map()->number==9); + Place(3,2,0);Key(sc_Space);CHECK(GameStep(++t) && GameIntermission()); + CHECK(gamestate.score==score+60000+15000); + Key(sc_Enter);CHECK(GameStep(++t) && CA_Map()->number==1); + GameStop(); +} +static void TestPushwalls(void) +{ + static const int dx[]={1,0,-1,0},dy[]={0,-1,0,1}; + for (unsigned d=0;d<4;++d) { + CHECK(GameStart(0));Place(30-dx[d]*2,30-dy[d]*2,(int)d*90); + tilemap[30][30]=1;pushable[30][30]=true; + int nx=30+dx[d],ny=30+dy[d]; + tilemap[nx][ny]=1;PushWall(30,30,(int)d*2);CHECK(!pwallstate && pushable[30][30]); + tilemap[nx][ny]=0;staticblock[nx][ny]=true;PushWall(30,30,(int)d*2);CHECK(!pwallstate); + staticblock[nx][ny]=false;actorat[nx][ny]=&objlist[0];PushWall(30,30,(int)d*2);CHECK(!pwallstate);actorat[nx][ny]=NULL; + PushWall(30,30,(int)d*2);CHECK(pwallstate==1 && !pwallpos && gamestate.secretcount==1 && !pushable[30][30]); + CHECK(tilemap[30][30]==193 && tilemap[nx][ny]==1); + objtype mover=player;mover.dir=(int)d*2;mover.tilex=30-dx[d];mover.tiley=30-dy[d];CHECK(!TryWalk(&mover)); + rayhit first,middle;CHECK(AsmRefresh((int)d*900,&first)); + for (unsigned i=0;i<63;++i) MovePWalls(); + CHECK(pwallstate==64 && pwallpos==32 && AsmRefresh((int)d*900,&middle)); + CHECK(first.side==(d%2 ? 3 : 4) && middle.side==first.side && middle.heightnumber==ep*10+map);CHECK(ThreeDRefresh() && DrawStatus());++supported; + for (unsigned tic=0;tic<140;++tic) { + ConnectAreas(); + for (objtype *ob=player.next;ob;ob=ob->next) DoActor(ob); + CHECK(!ActorAllocationFailed()); + if (tic%10==0) CHECK(ThreeDRefresh()); + } + ShutdownGameLevel(); + } + printf("Owned WL6: %u map/difficulty combinations load, render and simulate safely.\n",supported); + CHECK(supported==240); +} +int main(int argc,char **argv) +{ + CHECK(argc==2 || argc==3);MM_Startup();CHECK(CA_Startup(argv[1]));CHECK(VL_SetPalette(gamepal,768)); + if (argc==3) TestOwned(); + else { TestDifficulty();TestStats();TestProgression();TestPushwalls(); } + GameStop();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); + puts("Campaign selection, difficulty, exits, ratios, inventory, restarts and pushwalls passed.");return 0; +} diff --git a/tests/classic_tests.c b/tests/classic_tests.c new file mode 100644 index 00000000..201740ef --- /dev/null +++ b/tests/classic_tests.c @@ -0,0 +1,317 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_DEF.h" +#include "engine/WL_DEMO.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_MENU.h" +#include "engine/WL_SAVE.h" +#include "engine/WL_HIGHSCORES.h" +#include "engine/WL_CONTROLS.h" +#include "engine/WL_DISPLAY.h" +#include "engine/ID_CA.h" +#include "engine/ID_IN.h" +#include "engine/ID_VH.h" +#include "engine/ID_US_1.h" +#include "engine/ID_SD.h" +#include "platform/sdl_video.h" +#include "platform/sdl_input.h" +#include "platform/sdl_input.h" +#include +#include +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s)\n",__LINE__,#x,CA_Error());exit(1); } } while(0) +#include "finish_loading.h" +static uint64_t ticks; +/* Check before the legacy helper can drain an unintended loading screen. */ +static bool forbid_loading; +static void Step(unsigned n) { while(n--) { CHECK(!VL_PollQuit());CHECK(DemoLoop(++ticks));CHECK(!forbid_loading || (!GameLoading() && !GamePreloadPending()));if(GameLoading()) TestFinishLoading(ticks);CHECK(VW_UpdateScreen()); } } +static void Tap(SDL_Scancode key) { SDL_Event e={0};e.type=SDL_EVENT_KEY_DOWN;e.key.scancode=key;CHECK(SDL_PushEvent(&e));e.type=SDL_EVENT_KEY_UP;CHECK(SDL_PushEvent(&e));Step(1); } +static void Start(void) { CHECK(NewViewSize(15));CHECK(DemoLoopStartup(ticks,true));CHECK(DemoLoopStartGame(ticks));Step(10);CHECK(DemoLoopState()==UI_GAME); } +static void FKey(SDL_Scancode key,ui_state state) { Tap(key);Step(20);CHECK(DemoLoopState()==state); } +static void Back(void) { Tap(SDL_SCANCODE_ESCAPE);Step(20);CHECK(DemoLoopState()==UI_GAME); } +static void Capture(const char *name) { const char *dir=getenv("WOLF3D_CAPTURE_DIR");if(dir) { char p[4096];(void)snprintf(p,sizeof(p),"%s/%s.bmp",dir,name);CHECK(VL_Capture(p)); } } +static void Border(void) +{ + for(int y=0;y<160;++y) for(int x=0;x<320;++x) { + if(x>=VIEWX && x=VIEWY && y=VIEWX-1 && x<=VIEWX+VIEWWIDTH && y>=VIEWY-1 && y<=VIEWY+VIEWHEIGHT) color=0; + if((x==VIEWX+VIEWWIDTH || y==VIEWY+VIEWHEIGHT) && x>=VIEWX-1 && x<=VIEWX+VIEWWIDTH && y>=VIEWY-1 && y<=VIEWY+VIEWHEIGHT) color=125; + /* Original top-right is overwritten by the right vertical bevel. */ + if(x==VIEWX-1 && y==VIEWY+VIEWHEIGHT) color=124; + CHECK(framebuffer[y*320+x]==color); + } +} +static void Views(void) +{ + CHECK(GameStart(0));CHECK(Save_Write(0,"before view",true)); + for(unsigned size=4;size<=19;++size) { + unsigned rng=US_RndIndex();uint32_t time=gamestate.TimeCount; + CHECK(NewViewSize(size));CHECK(ViewSize()==size && VIEWWIDTH==size*16 && VIEWHEIGHT==size*8); + CHECK(VIEWX==(320-VIEWWIDTH)/2 && VIEWY==(160-VIEWHEIGHT)/2); + CHECK(GameDrawPaused());Border(); + CHECK(US_RndIndex()==rng && gamestate.TimeCount==time); + for(int i=0;i +#include +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%d: %s (%s)\n",__LINE__,#x,CA_Error());exit(1); } } while (0) +extern statetype s_grdstand,s_grdpath1,s_grdchase1,s_grdshoot1,s_grdshoot2,s_grdpain,s_grdpain1,s_grddie1,s_grddie4,s_dogjump1,s_dogjump2; +#include "finish_loading.h" +static objtype *Guard(void) { for (unsigned i=0;itilex==5 && guard->tiley==2 && guard->dir==west && guard->hitpoints==25 && guard->state==&s_grdstand); + CHECK(objlist[1].obclass==dogobj && objlist[1].tilex==8 && objlist[1].tiley==5 && objlist[1].x==9*65536+32768); + CHECK(!actorat[9][5] && actorat[8][5]==&objlist[1]); + CHECK(staticblock[3][4] && !staticblock[3][5]); + objtype test=player;test.x=3*65536+32768;test.y=4*65536+32768;CHECK(!TryMove(&test)); + test.y=5*65536+32768;CHECK(TryMove(&test)); + test.x=guard->x-MINACTORDIST;test.y=guard->y;CHECK(!TryMove(&test)); + test.x-=1;CHECK(TryMove(&test)); + GameStop();CHECK(!objcount && !statcount && !player.next && !CA_Map() && !ChunksInFile); +} +static void TestSprites(void) +{ + CHECK(GameStart(0));objtype *guard=Guard();CHECK(guard); + TransformActor(guard);CHECK(guard->viewheight>0 && guard->viewx==VIEWWIDTH/2-1 && guard->transx>2*65536); + CHECK(guard->flags&FL_VISABLE);CHECK(CalcRotate(guard)==0); + guard->dir=east;CHECK(CalcRotate(guard)==4);guard->dir=west; + guard->state=&s_grdpain;CHECK(CalcRotate(guard)==0);guard->dir=east;CHECK(CalcRotate(guard)==4); + guard->state=&s_grdstand;guard->x=player.x-65536;TransformActor(guard);CHECK(!guard->viewheight); + int x,height;CHECK(!TransformTile(5,2,&x,&height) && height>0 && x==VIEWWIDTH/2-1); + player.x+=20000;CHECK(TransformTile(3,2,&x,&height)); + memset(framebuffer,201,VL_PIXELS);memset(wallheight,0,sizeof(wallheight)); + CHECK(ScaleShape(120,0,256)); + CHECK(framebuffer[(VIEWY+60)*320+VIEWX+119]==100); + CHECK(framebuffer[(VIEWY+60)*320+VIEWX+118]==201); /* transparency */ + CHECK(framebuffer[(VIEWY+59)*320+VIEWX+119]==201); + wallheight[119]=256;memset(framebuffer,201,VL_PIXELS);CHECK(ScaleShape(120,0,256)); + CHECK(framebuffer[(VIEWY+60)*320+VIEWX+119]==201); /* equality occludes */ + CHECK(SimpleScaleShape(120,0,64));CHECK(framebuffer[(VIEWY+60)*320+VIEWX+119]==100); + /* Equal screen positions must be sorted by original projected height. */ + InitObjects();statcount=2; + statobjlist[0]=(statobj_t){4,2,SPR_STAT_0,dressing,false}; + statobjlist[1]=(statobj_t){5,2,SPR_STAT_1,dressing,false}; + unsigned char *near=(unsigned char *)PM_GetPage(PMSpriteStart+SPR_STAT_0,NULL); + unsigned char *far=(unsigned char *)PM_GetPage(PMSpriteStart+SPR_STAT_1,NULL); + memset(near+14,10,32);memset(far+14,20,32); + memset(framebuffer,201,VL_PIXELS);memset(wallheight,0,sizeof(wallheight)); + spotvis[4][2]=spotvis[5][2]=true;player.x=2*65536+32768; + CHECK(DrawScaleds());CHECK(framebuffer[(VIEWY+61)*320+VIEWX+119]==10); + statobj_t tmp=statobjlist[0];statobjlist[0]=statobjlist[1];statobjlist[1]=tmp; + memset(framebuffer,201,VL_PIXELS);CHECK(DrawScaleds());CHECK(framebuffer[(VIEWY+61)*320+VIEWX+119]==10); + memset(near+14,0,32);CHECK(DrawScaleds());CHECK(framebuffer[(VIEWY+61)*320+VIEWX+119]==0); /* opaque index zero */ + /* A nearer wall clips the actual world actor. */ + CHECK(GameStart(0));guard=Guard();for(int y=1;y<63;++y) tilemap[4][y]=1; + CHECK(ThreeDRefresh());CHECK(!(guard->flags&FL_VISABLE)); + GameStop(); +} +static statobj_t Bonus(stat_t item) { return (statobj_t){3,3,SPR_STAT_24,item,true}; } +static void TestPickups(void) +{ + CHECK(GameStart(0));statobj_t ob=Bonus(bo_food);GetBonus(&ob);CHECK(ob.shapenum!=-1 && gamestate.health==100); + gamestate.health=80;GetBonus(&ob);CHECK(ob.shapenum==-1 && gamestate.health==90); + ob=Bonus(bo_firstaid);GetBonus(&ob);CHECK(gamestate.health==100); + ob=Bonus(bo_alpo);gamestate.health=1;GetBonus(&ob);CHECK(gamestate.health==5); + ob=Bonus(bo_gibs);gamestate.health=11;GetBonus(&ob);CHECK(ob.shapenum!=-1); + gamestate.health=10;GetBonus(&ob);CHECK(gamestate.health==11 && ob.shapenum==-1); + gamestate.ammo=99;ob=Bonus(bo_clip);GetBonus(&ob);CHECK(ob.shapenum!=-1); + gamestate.ammo=94;GetBonus(&ob);CHECK(gamestate.ammo==99 && ob.shapenum==-1); + gamestate.ammo=0;gamestate.weapon=wp_knife;GiveAmmo(4);CHECK(gamestate.weapon==wp_pistol && gamestate.ammo==4); + ob=Bonus(bo_machinegun);GetBonus(&ob);CHECK(gamestate.bestweapon==wp_machinegun && gamestate.ammo==10); + ob=Bonus(bo_chaingun);GetBonus(&ob);CHECK(gamestate.weapon==wp_chaingun && gamestate.ammo==16); + CHECK(DrawStatus() && framebuffer[164*320+17*8]==GOTGATLINGPIC); + ob=Bonus(bo_crown);GetBonus(&ob);CHECK(gamestate.score==5000 && gamestate.treasurecount==1); + GivePoints(35000);CHECK(gamestate.lives==4 && gamestate.nextextra==80000); + ob=Bonus(bo_key1);GetBonus(&ob);CHECK(gamestate.keys==1); + doorobjlist[0].lock=1;OperateDoor(0);CHECK(doorobjlist[0].action==dr_opening); + /* Rendering uses the original projected getting distance, not tile equality. */ + CHECK(GameStart(0));player.x=3*65536+32768;player.y=2*65536+52768;player.tilex=3;player.angle=270; + gamestate.health=80;CHECK(ThreeDRefresh());CHECK(gamestate.health==90); + GameStop(); +} +static void TestSightStates(void) +{ + CHECK(GameStart(0));objtype *guard=Guard();CHECK(CheckLine(guard) && CheckSight(guard)); + guard->dir=east;CHECK(!CheckSight(guard));guard->dir=west; + tilemap[4][2]=1;CHECK(!CheckLine(guard) && !CheckSight(guard)); + US_InitRndT(0);CHECK(!SightPlayer(guard) && !guard->temp2); + madenoise=true;CHECK(!SightPlayer(guard) && guard->temp2==3);madenoise=false; + CHECK(!SightPlayer(guard));CHECK(!SightPlayer(guard));CHECK(SightPlayer(guard)); + CHECK(guard->state==&s_grdchase1 && guard->speed==SPDPATROL*3 && (guard->flags&FL_ATTACKMODE)); + tilemap[4][2]=0;guard->x=player.x+65536;guard->y=player.y;guard->tilex=3;guard->tiley=2; + US_InitRndT(0);T_Chase(guard);CHECK(guard->state==&s_grdshoot1); + /* The shoot action runs after 20+20 tics, on leaving shoot2. */ + int health=gamestate.health;NewState(guard,&s_grdshoot1); + for(unsigned i=0;i<39;++i) DoActor(guard); + CHECK(gamestate.health==health && guard->state==&s_grdshoot2); + US_InitRndT(0);DoActor(guard);CHECK(gamestate.health==health-27); + guard->x=5*65536+32768;guard->tilex=5;tilemap[4][2]=1;health=gamestate.health;US_InitRndT(0);T_Shoot(guard);CHECK(gamestate.health==health);tilemap[4][2]=0; + /* Ambush ignores hearing; disconnected areas reject activation. */ + CHECK(GameStart(0));guard=Guard();guard->flags|=FL_AMBUSH;tilemap[4][2]=1;madenoise=true; + CHECK(!SightPlayer(guard) && !guard->temp2); + tilemap[4][2]=0;areabyplayer[guard->areanumber]=false;CHECK(!SightPlayer(guard)); + GameStop(); +} +static void TestMovement(void) +{ + CHECK(GameStart(0));objtype *guard=Guard(); + guard->dir=southwest;tilemap[guard->tilex-1][guard->tiley]=1;CHECK(!TryWalk(guard));tilemap[guard->tilex-1][guard->tiley]=0; + guard->dir=east;CHECK(TryWalk(guard) && guard->tilex==6 && guard->distance==-1 && doorobjlist[0].action==dr_opening); + /* The reservation becomes blocking when DoActor marks the grid. */ + actorat[guard->tilex][guard->tiley]=guard; + doorobjlist[0].position=65535;doorobjlist[0].action=dr_open;CloseDoor(0);CHECK(doorobjlist[0].action==dr_open); + CHECK(GameStart(0));guard=Guard();guard->x=player.x+MINACTORDIST+100;guard->y=player.y;guard->dir=west;guard->distance=65536; + int32_t x=guard->x;MoveObj(guard,200);CHECK(guard->x==x && guard->distance==65536); + MoveObj(guard,50);CHECK(guard->x==x-50 && guard->distance==65486); + CHECK(GameStart(0)); + objtype *dog=&objlist[1];dog->x=player.x+65536;dog->y=player.y; + dog->dir=west;dog->distance=65536;T_DogChase(dog);CHECK(dog->state==&s_dogjump1); + int health=gamestate.health;US_InitRndT(0);T_Bite(dog);CHECK(gamestate.health==health-6); + CHECK(GameStart(0)); + dog=&objlist[1];dog->flags|=FL_AMBUSH;dog->dir=west; + int32_t original=dog->x;DoActor(dog);CHECK(dog->x==original-SPDDOG); + /* A map arrow replaces the current patrol direction, reserving its cell. */ + actorat[dog->tilex][dog->tiley]=NULL;dog->tilex=26;dog->tiley=1;dog->dir=east; + SelectPathDir(dog);CHECK(dog->tilex==25 && dog->tiley==1 && dog->dir==west); + GameStop(); +} +static void TestAreas(void) +{ + CHECK(GameStart(0));areaMap[2][2]=areaMap[5][2]=1;areaMap[7][2]=2; + ConnectAreas();CHECK(areabyplayer[1] && !areabyplayer[2]); + OpenDoor(0);ConnectAreas();CHECK(!areabyplayer[2]); + MoveDoors();ConnectAreas();CHECK(areabyplayer[2]); + doorobjlist[0].action=dr_closing;MoveDoors();ConnectAreas();CHECK(!areabyplayer[2]); + GameStop(); +} +static void TestCombat(void) +{ + CHECK(GameStart(0));objtype *guard=Guard();US_InitRndT(0);DamageActor(guard,3); + CHECK(guard->hitpoints==19 && (guard->state==&s_grdpain || guard->state==&s_grdpain1)); + CHECK(guard->flags&FL_ATTACKMODE);DamageActor(guard,3);CHECK(guard->hitpoints==16); + DamageActor(guard,100);CHECK(guard->state==&s_grddie1 && !(guard->flags&FL_SHOOTABLE)); + CHECK(gamestate.score==100 && gamestate.killcount==1 && statcount==9 && statobjlist[8].itemnumber==bo_clip2); + for(unsigned i=0;i<45;++i) { DoActor(guard); } + CHECK(guard->state==&s_grddie4); + CHECK(GameStart(0));guard=Guard(); + T_Attack(true);CHECK(gamestate.weaponframe==1 && gamestate.ammo==8); + for(unsigned t=0;t<11;++t) T_Attack(true); + CHECK(gamestate.ammo==8);US_InitRndT(0);T_Attack(true); + CHECK(gamestate.ammo==7 && guard->hitpoints==23); /* RNG 8 / 6, doubled surprise. */ + for(unsigned t=0;t<12;++t) T_Attack(true); + CHECK(!gamestate.attackframe);for(unsigned t=0;t<50;++t) T_Attack(true);CHECK(gamestate.ammo==7); /* pistol is semi-auto */ + T_Attack(false);T_Attack(true);for(unsigned t=0;t<12;++t) T_Attack(true);CHECK(gamestate.ammo==6); + CHECK(GameStart(0));GiveWeapon(wp_machinegun);int ammo=gamestate.ammo; + T_Attack(true);for(unsigned t=0;t<36;++t) T_Attack(true);CHECK(gamestate.ammo==ammo-3); + CHECK(GameStart(0));GiveWeapon(wp_chaingun);ammo=gamestate.ammo; + T_Attack(true);for(unsigned t=0;t<36;++t) T_Attack(true);CHECK(gamestate.ammo==ammo-5); + CHECK(GameStart(0));gamestate.ammo=1;T_Attack(true);for(unsigned t=0;t<24;++t) T_Attack(true);CHECK(gamestate.ammo==0 && gamestate.weapon==wp_knife); + IN_KeyEvent(0x02,true);T_Attack(false);CHECK(gamestate.weapon==wp_knife);IN_ClearKeysDown(); + TakeDamage(1,Guard());CHECK(gamestate.health==99 && !gamestate.died);TakeDamage(100,Guard());CHECK(gamestate.health==0 && gamestate.died); + CHECK(GameStart(0));guard=Guard();guard->obclass=ssobj;DamageActor(guard,1000); + CHECK(statobjlist[statcount-1].itemnumber==bo_machinegun && gamestate.score==500); + CHECK(GameStart(0));guard=Guard();guard->x=player.x+65536;guard->tilex=3; + CHECK(ThreeDRefresh());gamestate.weapon=wp_knife;US_InitRndT(0); + T_Attack(true);for(unsigned t=0;t<12;++t) T_Attack(true);CHECK(gamestate.ammo==8 && guard->hitpoints==25); /* 8 >> 4 = 0 */ + CHECK(GameStart(0));GiveWeapon(wp_chaingun);IN_KeyEvent(0x03,true);T_Attack(false); + CHECK(gamestate.weapon==wp_pistol && gamestate.chosenweapon==wp_pistol);IN_ClearKeysDown(); + gamestate.ammo=0;gamestate.weapon=wp_knife;IN_KeyEvent(0x05,true);T_Attack(false);CHECK(gamestate.weapon==wp_knife);IN_ClearKeysDown(); + CHECK(GameStart(0));GiveWeapon(wp_chaingun); + IN_KeyEvent(0x02,true);IN_KeyEvent(0x05,true);T_Attack(false); + CHECK(gamestate.weapon==wp_knife && gamestate.chosenweapon==wp_knife);IN_ClearKeysDown(); + gamestate.chosenweapon=wp_pistol;gamestate.ammo=0; + IN_KeyEvent(0x02,true);T_Attack(false);CHECK(gamestate.chosenweapon==wp_pistol);IN_ClearKeysDown(); + GiveAmmo(8);CHECK(gamestate.weapon==wp_pistol); + GameStop(); +} +static void TestHud(void) +{ + CHECK(GameStart(0));CHECK(framebuffer[176*320+14*8]==N_0PIC+3); + CHECK(framebuffer[176*320+23*8]==N_0PIC);CHECK(framebuffer[176*320+28*8]==N_0PIC+8); + gamestate.health=7;gamestate.ammo=42;gamestate.score=123;gamestate.keys=1;gamestate.weapon=wp_machinegun; + CHECK(DrawStatus());CHECK(framebuffer[176*320+23*8]==N_0PIC+7); + CHECK(framebuffer[176*320+27*8]==N_0PIC+4 && framebuffer[176*320+28*8]==N_0PIC+2); + CHECK(framebuffer[164*320+30*8]==GOLDKEYPIC);CHECK(framebuffer[168*320+32*8]==MACHINEGUNPIC); + CHECK(framebuffer[164*320+17*8]==FACE1APIC+3*5+gamestate.faceframe); + US_InitRndT(0);int first=-1; + for(unsigned i=0;i<256;++i) { UpdateFace();CHECK(gamestate.faceframe>=0 && gamestate.faceframe<=2);if(gamestate.faceframe) first=1; } + CHECK(first==1); + GameStop(); +} +static void TestTicsDeath(void) +{ + CHECK(GameStart(0));IN_KeyEvent(sc_UpArrow,true);CHECK(GameStep(9)); + objtype fine[MAXACTORS];gametype state=gamestate;memcpy(fine,objlist,sizeof(fine)); + CHECK(GameStart(0));IN_KeyEvent(sc_UpArrow,true);for(uint64_t t=1;t<=9;++t) CHECK(GameStep(t)); + CHECK(gamestate.health==state.health && gamestate.ammo==state.ammo && gamestate.faceframe==state.faceframe); + for(unsigned i=0;i=0;--life) { + CHECK(gamestate.lives==life);TakeDamage(100,Guard()); + unsigned steps=0;while(gamestate.died && !GameFinished() && steps++<500) CHECK(GameStep(++ticks)); + CHECK(steps<500); + if(life) CHECK(!GameFinished() && gamestate.health==100 && gamestate.ammo==8 && gamestate.lives==life-1); + } + CHECK(GameFinished() && gamestate.lives==-1); + GameStop(); +} +static void TestFlashes(void) +{ + CHECK(GameStart(0));StartBonusFlash();CHECK(UpdatePaletteShifts()); + for(unsigned j=0;j<768;++j) { + int base=gamepal[j],target=j%3==0?64:j%3==1?62:0; + CHECK(palette[j]==base+(target-base)*3/20); + } + StartDamageFlash(10);CHECK(UpdatePaletteShifts()); + for(unsigned j=0;j<768;++j) { + int base=gamepal[j],target=j%3==0?64:0; + CHECK(palette[j]==base+(target-base)*2/8); + } + for(unsigned i=0;i<20;++i) CHECK(UpdatePaletteShifts()); + CHECK(!memcmp(palette,gamepal,768));GameStop(); +} +static void TestMalformedSprites(void) +{ + CHECK(GameStart(0)); + unsigned char *page=(unsigned char *)PM_GetPage(PMSpriteStart,NULL),saved[46]; + memcpy(saved,page,46); + unsigned char pixels[4098],mask[4098];uint32_t seed=5; + for(unsigned attempt=0;attempt<1000;++attempt) { + memcpy(page,saved,46);seed=seed*1664525U+1013904223U; + page[seed%46]^=(unsigned char)(seed>>24); + memset(pixels,0x57,sizeof(pixels));memset(mask,0x57,sizeof(mask)); + (void)PM_DecodeSprite(0,pixels+1,mask+1); + CHECK(pixels[0]==0x57 && pixels[4097]==0x57 && mask[0]==0x57 && mask[4097]==0x57); + } + memcpy(page,saved,46); + /* Asymmetric command columns must use the original right-half anchor. */ + page[0]=43;page[2]=43;memset(framebuffer,201,VL_PIXELS); + CHECK(SimpleScaleShape(120,0,64)); + CHECK(framebuffer[(VIEWY+60)*320+VIEWX+120]==100); + CHECK(framebuffer[(VIEWY+60)*320+VIEWX+131]==201); + memcpy(page,saved,46);GameStop(); +} +static void TestGameOverMenu(void) +{ + CHECK(DemoLoopStartGame(0));CHECK(DemoLoop(10));TestFinishLoading(10);gamestate.lives=0;TakeDamage(100,Guard()); + uint64_t ticks=10; + while(DemoLoopState()==UI_GAME && ticks<600) CHECK(DemoLoop(++ticks)); + CHECK(DemoLoopState()==UI_RESULTS && !CA_Map() && !ChunksInFile); + CHECK(DemoLoop(ticks+30));IN_KeyEvent(sc_Enter,true);IN_KeyEvent(sc_Enter,false); + CHECK(DemoLoop(ticks+31) && DemoLoop(ticks+61) && DemoLoopState()==UI_TITLE); +} +static void TestOwnedCombat(void) +{ + CHECK(GameStart(0));CHECK(objcount==21 && statcount==121 && gamestate.killtotal==20 && gamestate.treasuretotal==23); + objtype *guard=NULL; + for(unsigned i=0;itilex+dx[d];player.tiley=ob->tiley+dy[d]; + player.x=player.tilex*65536+32768;player.y=player.tiley*65536+32768;player.angle=angle[d]; + if(TryMove(&player) && CheckLine(ob)) { guard=ob;break; } + } + } + CHECK(guard && ThreeDRefresh() && (guard->flags&FL_VISABLE)); + uint64_t ticks=0; + /* Aim with the actual angle and use real input/tics; no damage override. */ + for(unsigned shot=0;shot<8 && (guard->flags&FL_SHOOTABLE) && !gamestate.died;++shot) { + IN_KeyEvent(0x1d,true); + for(unsigned j=0;j<25;++j) { + double a=atan2((double)player.y-guard->y,(double)guard->x-player.x); + if(a<0) a+=6.28318530717958647692; + player.angle=(int)(a/6.28318530717958647692*360); + CHECK(GameStep(++ticks)); + } + IN_KeyEvent(0x1d,false);CHECK(GameStep(++ticks)); + } + CHECK(!(guard->flags&FL_SHOOTABLE) && gamestate.killcount>0 && gamestate.score>=100 && gamestate.ammo<8); + GameStop(); +} +int main(int argc,char **argv) +{ + CHECK(argc==2 || argc==3);MM_Startup();CHECK(CA_Startup(argv[1]));CHECK(VL_SetPalette(gamepal,768)); + if(argc==3) TestOwnedCombat(); + else { TestRandom();TestSpawn();TestSprites();TestPickups();TestSightStates();TestMovement();TestAreas();TestCombat();TestHud();TestTicsDeath();TestFlashes();TestMalformedSprites();TestGameOverMenu(); } + GameStop();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); + puts("Original sprite/object/RNG/AI/combat/HUD/death tests passed.");return 0; +} diff --git a/tests/config_tests.c b/tests/config_tests.c new file mode 100644 index 00000000..573831da --- /dev/null +++ b/tests/config_tests.c @@ -0,0 +1,148 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "platform/config_file.h" +#include "platform/save_file.h" +#include "platform/sdl_video.h" +#include "engine/WL_CONTROLS.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_MENU.h" +#include "engine/WL_DISPLAY.h" +#include "engine/WL_SAVE.h" +#include "engine/ID_CA.h" +#include "engine/ID_SD.h" +#include "engine/ID_US_1.h" +#include "engine/ID_IN.h" +#include +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s; %s)\n",__LINE__,#x,Config_Error(),SDL_GetError());exit(1); } } while(0) +#include "finish_loading.h" +static const char *directory; +static SDL_Window *window; +static void Pump(void) { CHECK(!VL_PollQuit());CHECK(VW_UpdateScreen()); } +static void Await(void) +{ + Uint64 until=SDL_GetTicks()+4000;display_settings d; + do { Pump();CHECK(VL_DisplayGet(&d));if(!d.pending) break;SDL_Delay(5); } while(SDL_GetTicks()0); } +static void Write(const void *data,size_t length) +{ char p[4096];Path(p);FILE *f=fopen(p,"wb");CHECK(f);CHECK(fwrite(data,1,length,f)==length);CHECK(fclose(f)==0); } +static size_t Read(char out[8192]) +{ char p[4096];Path(p);FILE *f=SaveFile_Open(p);CHECK(f);size_t n=fread(out,1,8192,f);CHECK(!ferror(f));CHECK(fclose(f)==0);return n; } +static void JSON(config_result result) +{ + unsigned m,e;bool mon,eon;SD_GetSettings(&m,&e,&mon,&eon);display_settings d;CHECK(VL_DisplayPreferences(&d)); + printf("{\"result\":%d,\"preset\":%d,\"music\":%u,\"effects\":%u,\"music_on\":%d,\"effects_on\":%d,\"view\":%u,\"fullscreen\":%d,\"integer\":%d,\"width\":%d,\"height\":%d,\"high_resolution\":%d,\"render_auto\":%d,\"render_width\":%u,\"render_height\":%u,\"aspect\":%u,\"vsync\":%d,\"linear\":%d,\"smooth\":%d,\"profiles\":[",result,(int)CT_Preset(),m,e,mon,eon,ViewSize(),d.fullscreen,d.integer,d.width,d.height,d.high_resolution,d.render_auto,d.render_width,d.render_height,d.aspect,d.vsync,d.linear,d.smooth); + for(unsigned i=0;i<2;++i) { + ct_profile p;CT_GetProfile((ct_preset)i,&p);printf("%s{\"mouse\":%d,\"invert\":%d,\"sensitivity\":%u,\"bindings\":[",i?",":"",p.mouse,p.invert,p.sensitivity); + for(unsigned a=0;a>24); } + Write(bytes,n);(void)Config_Load(directory);CHECK(US_RndIndex()==rng); + } + JSON(CONFIG_INVALID); +} +static void Game(const char *data) +{ + CHECK(CA_Startup(data));CHECK(Save_SetDirectory(directory));Display_Connect(VL_DisplayGet,VL_DisplaySet); + CHECK(DemoLoopStartup(0,true));CHECK(DemoLoopStartGame(0));CHECK(DemoLoop(10));TestFinishLoading(10); + CHECK(Save_Write(0,"before config",true));unsigned rng=US_RndIndex();uint32_t t=gamestate.TimeCount; + CHECK(Config_Save(directory));CHECK(Config_Load(directory)==CONFIG_LOADED);Await();CHECK(GameDrawPaused());CHECK(Save_Write(1,"after config",true)); + CHECK(US_RndIndex()==rng && gamestate.TimeCount==t); + IN_KeyEvent(0x3b,true);IN_KeyEvent(0x3b,false);CHECK(DemoLoop(11));CHECK(DemoLoop(31));CHECK(DemoLoopState()==UI_BOSS); + DemoLoopPrepareExit();unsigned m,e;bool on,fx;SD_GetSettings(&m,&e,&on,&fx);CHECK(on && fx);CHECK(Config_Save(directory)); + GameStop();Display_Connect(NULL,NULL);JSON(CONFIG_LOADED); +} +int main(int argc,char **argv) +{ + CHECK(argc==4);directory=argv[1];MM_Startup();CHECK(VL_Startup());int count;SDL_Window **windows=SDL_GetWindows(&count);CHECK(windows && count==1);window=windows[0];SDL_free(windows);Reset(); + const char *mode=argv[3]; + if(!strcmp(mode,"inspect")) { config_result r=Config_Load(directory);Await();JSON(r); } + else if(!strcmp(mode,"migrate")) { CHECK(Config_Load(directory)==CONFIG_LOADED);CHECK(Config_Save(directory));JSON(CONFIG_LOADED); } + else if(!strcmp(mode,"roundtrip")) Roundtrip(); + else if(!strcmp(mode,"seed")) { Seed();CHECK(Config_Save(directory));JSON(CONFIG_LOADED); } + else if(!strcmp(mode,"atomic")) Atomic(); + else if(!strcmp(mode,"profiles")) Profiles(); + else if(!strcmp(mode,"display")) Display(); + else if(!strcmp(mode,"fuzz")) Fuzz(); + else if(!strcmp(mode,"paths")) { + CHECK(Config_Load(NULL)==CONFIG_IO_ERROR && !Config_Save(NULL));char longpath[5000];memset(longpath,'a',sizeof(longpath)-1);longpath[sizeof(longpath)-1]=0; + CHECK(Config_Load(longpath)==CONFIG_IO_ERROR && !Config_Save(longpath));JSON(CONFIG_IO_ERROR); + } + else if(!strcmp(mode,"game")) Game(argv[2]); + else if(!strcmp(mode,"save")) { bool ok=Config_Save(directory);printf("{\"saved\":%d}\n",ok); } + else if(!strcmp(mode,"prefpath")) { char *p=SDL_GetPrefPath(NULL,"wolf3d-revive");CHECK(p);directory=p;CHECK(Config_Save(p));SDL_free(p);JSON(CONFIG_LOADED); } + else if(!strcmp(mode,"unicode")) { + static char path[4096];CHECK(snprintf(path,sizeof(path),"%s/caf\xc3\xa9-\xe8\xa8\xad\xe5\xae\x9a",directory)>0);CHECK(SDL_CreateDirectory(path));directory=path; + CHECK(Config_Save(path));CHECK(Config_Load(path)==CONFIG_LOADED);JSON(CONFIG_LOADED); + } else CHECK(false); + VL_Shutdown();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes());return 0; +} diff --git a/tests/controls_tests.c b/tests/controls_tests.c new file mode 100644 index 00000000..321f78cc --- /dev/null +++ b/tests/controls_tests.c @@ -0,0 +1,137 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_CONTROLS.h" +#include "engine/WL_SAVE.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_MENU.h" +#include "engine/ID_CA.h" +#include "engine/ID_IN.h" +#include "engine/ID_US_1.h" +#include "engine/ID_VL.h" +#include "platform/sdl_video.h" +#include "platform/sdl_input.h" +#include +#include +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s; %s)\n",__LINE__,#x,CA_Error(),SDL_GetError());exit(1); } } while(0) +#include "finish_loading.h" +static uint64_t ticks; +static void Arena(void) +{ + InitObjects();doornum=0;ResetPushwalls(); + for(int x=0;x<64;++x) for(int y=0;y<64;++y) { tilemap[x][y]=(uint8_t)((!x || !y || x==63 || y==63)?1:0);areaMap[x][y]=0; } + player.x=player.y=10*TILEGLOBAL+TILEGLOBAL/2;player.tilex=player.tiley=10;player.angle=0; + player.areanumber=0;player.flags=0;ResetMovement();IN_ClearKeysDown(); +} +static void One(void) { CHECK(GameStep(++ticks)); } +static void Reset(ct_preset preset) { CT_Reset(preset);CHECK(GameStart(ticks));Arena(); } +static double Distance(int32_t x,int32_t y) { return hypot((double)player.x-x,(double)player.y-y); } +static void Core(void) +{ + /* Equivalent forward inputs must leave the entire simulation identical, + including original enemies and gameplay RNG, in both presets. */ + CT_Reset(CT_CLASSIC);CHECK(GameStart(0));ticks=0;CT_Key(SDL_SCANCODE_UP,true); + for(unsigned i=0;i<20;++i) One(); + CHECK(Save_Write(4,"classic equivalent",true));unsigned equivalent_rng=US_RndIndex(); + CT_Reset(CT_MODERN);CHECK(GameStart(0));ticks=0;CT_Key(SDL_SCANCODE_W,true); + for(unsigned i=0;i<20;++i) One(); + CHECK(Save_Write(5,"modern equivalent",true) && US_RndIndex()==equivalent_rng); + Reset(CT_CLASSIC);int32_t x=player.x,y=player.y; + CT_Key(SDL_SCANCODE_W,true);One();CHECK(player.x==x && player.y==y);CT_Clear(); + CT_Key(SDL_SCANCODE_UP,true);One();CHECK(player.x==x+5249 && player.y==y); + Arena();CT_Key(SDL_SCANCODE_UP,true);CT_Key(SDL_SCANCODE_LSHIFT,true);One();CHECK(player.x==x+10499); + Arena();CT_Key(SDL_SCANCODE_RIGHT,true);One();CHECK(player.angle==359 && player.x==x); + Arena();CT_Key(SDL_SCANCODE_RIGHT,true);CT_Key(SDL_SCANCODE_LALT,true);One();CHECK(player.angle==0 && player.y==y+5249); + Arena();CT_Key(SDL_SCANCODE_UP,true);CT_Key(SDL_SCANCODE_DOWN,true);One();CHECK(player.x==x && player.y==y); + Arena();CT_Key(SDL_SCANCODE_KP_8,true);One();CHECK(player.x==x+5249); + Arena();CHECK(CT_Bind(CT_STRAFE_LEFT,0,SDL_SCANCODE_A));CT_Key(SDL_SCANCODE_A,true);One();CHECK(player.y==y-5249); + Reset(CT_MODERN);CT_Key(SDL_SCANCODE_W,true);One();double axial=Distance(x,y);CHECK(axial==5249); + Arena();CT_Key(SDL_SCANCODE_S,true);One();CHECK(player.x==x-3499); + Arena();CT_Key(SDL_SCANCODE_A,true);One();CHECK(player.y==y-5249 && player.angle==0); + Arena();CT_Key(SDL_SCANCODE_D,true);One();CHECK(player.y==y+5249 && player.angle==0); + Arena();CT_Key(SDL_SCANCODE_W,true);CT_Key(SDL_SCANCODE_UP,true);One();CHECK(Distance(x,y)==axial); + Arena();CT_Key(SDL_SCANCODE_W,true);CT_Key(SDL_SCANCODE_D,true);One();CHECK(Distance(x,y)<=axial && Distance(x,y)>axial-4 && thrustspeed==5250); + Arena();CT_Key(SDL_SCANCODE_W,true);CT_Key(SDL_SCANCODE_D,true);CT_Key(SDL_SCANCODE_LSHIFT,true);One();CHECK(Distance(x,y)<=10499 && Distance(x,y)>10495 && thrustspeed==10500); + Arena();CT_Key(SDL_SCANCODE_W,true);CT_Key(SDL_SCANCODE_S,true);CT_Key(SDL_SCANCODE_A,true);CT_Key(SDL_SCANCODE_D,true);One();CHECK(player.x==x && player.y==y); + Arena();CT_Key(SDL_SCANCODE_D,true);CT_Key(SDL_SCANCODE_LALT,true);CT_Key(SDL_SCANCODE_RIGHT,true);One();CHECK(player.y==y+5249); + Arena();CT_Key(SDL_SCANCODE_A,true);CT_Key(SDL_SCANCODE_LALT,true);CT_Key(SDL_SCANCODE_RIGHT,true);One();CHECK(player.x==x && player.y==y); + /* One clipped vector and one tile update; never move into a static block. */ + Arena();staticblock[11][10]=true;CT_Key(SDL_SCANCODE_W,true);for(unsigned i=0;i<12;++i) One();CHECK(player.tilex==10); + Arena();unsigned rng=US_RndIndex();CT_MouseMotion(2);CT_MouseMotion(2);CHECK(US_RndIndex()==rng);One();CHECK(player.angle==358); + Arena();CT_SetSensitivity(20);CT_MouseMotion(4);One();CHECK(player.angle==356); + Arena();CT_SetInvert(true);CT_MouseMotion(4);One();CHECK(player.angle==4); + Arena();CT_SetInvert(false);CT_MouseMotion(1e30);CT_Key(SDL_SCANCODE_RIGHT,true);One();CHECK(player.angle>=0 && player.angle<360); + Arena();CT_SetSensitivity(1);CT_MouseMotion(0.5);CHECK(CT_MouseTurn()==0);CT_MouseMotion(0.5);CHECK(CT_MouseTurn()==1); + CT_SetMouse(false);CT_MouseMotion(100);CT_MouseButton(1,true);CHECK(CT_MouseTurn()==0 && !CT_Down(CT_FIRE)); + CT_Reset(CT_MODERN);CT_MouseMotion(NAN);CT_MouseMotion(INFINITY);CT_MouseMotion(-INFINITY);CHECK(CT_MouseTurn()==0);CT_MouseButton(1,true);CT_MouseButton(1,false);CHECK(CT_Down(CT_FIRE));CT_EndTic();CHECK(!CT_Down(CT_FIRE)); + CT_MouseButton(3,true);CHECK(CT_Pressed(CT_USE) && !CT_Pressed(CT_USE));CT_Clear(); + CHECK(!CT_Bind(CT_FORWARD,0,SDL_SCANCODE_S) && CT_Binding(CT_FORWARD,0)==SDL_SCANCODE_W); + CHECK(!CT_Bind(CT_FIRE,0,SDL_SCANCODE_ESCAPE));CHECK(!CT_Bind(CT_FIRE,0,SDL_SCANCODE_F12));CHECK(!CT_Bind(CT_FIRE,2,4));CHECK(!CT_Bind(CT_FIRE,0,512)); + CHECK(CT_Bind(CT_FORWARD,0,SDL_SCANCODE_E));CT_Key(SDL_SCANCODE_W,true);CHECK(!CT_Down(CT_FORWARD));CT_Key(SDL_SCANCODE_E,true);CHECK(CT_Down(CT_FORWARD)); + CHECK(CT_Bind(CT_FORWARD,1,0) && CT_Bind(CT_FIRE,0,SDL_SCANCODE_UP)); + IN_KeyEvent(sc_UpArrow,true);CHECK(IN_ConsumePress(sc_UpArrow) && CT_Down(CT_FIRE));IN_ClearKeysDown(); + CHECK(CT_Bind(CT_WEAPON2,0,SDL_SCANCODE_R));gamestate.bestweapon=wp_chaingun;gamestate.weapon=wp_knife; + CT_Key(SDL_SCANCODE_2,true);CheckWeaponChange();CHECK(gamestate.weapon==wp_knife);CT_Clear(); + CT_Key(SDL_SCANCODE_R,true);CheckWeaponChange();CHECK(gamestate.weapon==wp_pistol); + CT_Reset(CT_CLASSIC);CHECK(CT_Binding(CT_FORWARD,0)==SDL_SCANCODE_UP && !CT_MouseEnabled()); + /* Controls/settings are not save-format fields. Restore angle fraction, + clear pending input, and leave the player's current settings intact. */ + Reset(CT_MODERN);CT_SetSensitivity(17);CT_MouseMotion(1);One();CHECK(Save_Write(0,"modern controls",true)); + CT_Reset(CT_CLASSIC);CHECK(Save_Load(0,ticks));CHECK(CT_Preset()==CT_CLASSIC && !CT_MouseEnabled()); + CHECK(Save_GetAngleFraction()==17);CT_Reset(CT_MODERN);CT_SetSensitivity(17); + CT_Key(SDL_SCANCODE_W,true);CT_MouseMotion(1);One();CHECK(Save_Write(1,"continuous",true));rng=US_RndIndex(); + CHECK(Save_Load(0,ticks-1));--ticks;CT_Key(SDL_SCANCODE_W,true);CT_MouseMotion(1);One(); + CHECK(Save_Write(2,"restored",true) && US_RndIndex()==rng); + puts("Classic/Modern movement, normalization, mouse, bindings and deterministic saves passed."); +} +static void Event(SDL_EventType type) +{ SDL_Event e={0};e.type=type;CHECK(SDL_PushEvent(&e)); } +static void Key(SDL_Scancode code,bool down) +{ SDL_Event e={0};e.type=down?SDL_EVENT_KEY_DOWN:SDL_EVENT_KEY_UP;e.key.scancode=code;CHECK(SDL_PushEvent(&e)); } +static void Step(unsigned n) { while(n--) { CHECK(!VL_PollQuit());CHECK(DemoLoop(++ticks));if(GameLoading()) TestFinishLoading(ticks);CHECK(VW_UpdateScreen()); } } +static void Tap(SDL_Scancode key) { Key(key,true);Key(key,false);Step(1); } +static void Mouse(unsigned button,bool down) +{ SDL_Event e={0};e.type=down?SDL_EVENT_MOUSE_BUTTON_DOWN:SDL_EVENT_MOUSE_BUTTON_UP;e.button.button=(uint8_t)button;CHECK(SDL_PushEvent(&e)); } +static void Capture(const char *name) +{ + const char *dir=getenv("WOLF3D_CAPTURE_DIR");if(!dir) return; + char path[4096];(void)snprintf(path,sizeof(path),"%s/%s.bmp",dir,name);CHECK(VL_Capture(path)); +} +static void SDLControls(void) +{ + CHECK(VL_Startup());CT_Reset(CT_CLASSIC);CHECK(DemoLoopStartup(ticks,true));Step(11);CHECK(!IN_SDLCaptured()); + MainItems.curpos=control;Tap(SDL_SCANCODE_RETURN);Step(21);CHECK(DemoLoopState()==UI_CONTROLS);Capture("controls-classic"); + Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_RETURN); /* Customize, skipping disabled devices/sensitivity. */ + Tap(SDL_SCANCODE_RETURN);CHECK(CT_Preset()==CT_MODERN && CT_MouseEnabled());Capture("controls-modern"); + for(unsigned i=0;i<5;++i) Tap(SDL_SCANCODE_DOWN); + Tap(SDL_SCANCODE_RETURN);Capture("controls-bindings");Tap(SDL_SCANCODE_RETURN);Tap(SDL_SCANCODE_S); + CHECK(CT_Binding(CT_FORWARD,0)==SDL_SCANCODE_W);Capture("controls-conflict");Tap(SDL_SCANCODE_E); + CHECK(CT_Binding(CT_FORWARD,0)==SDL_SCANCODE_E);Tap(SDL_SCANCODE_ESCAPE);Tap(SDL_SCANCODE_ESCAPE);Tap(SDL_SCANCODE_ESCAPE);Step(21); + CHECK(DemoLoopState()==UI_MENU);Mouse(1,true);Step(1);CHECK(!IN_SDLCaptured()); + CHECK(DemoLoopStartGame(ticks));Step(11);Arena();CHECK(IN_SDLCaptured()); + CHECK(!CT_Down(CT_FIRE)); + tilemap[11][10]=128;doornum=1;doorobjlist[0]=(doorobj_t){.x=11,.y=10,.vertical=true}; + Mouse(3,true);Step(1);CHECK(doorobjlist[0].action==dr_opening); + Step(1);CHECK(doorobjlist[0].position>0 && doorobjlist[0].action==dr_opening); + Mouse(3,false);Step(1);Arena(); + Mouse(1,false);Mouse(1,true);Step(1);CHECK(gamestate.attackframe==1);Mouse(1,false);Step(1); + int angle=player.angle;SDL_Event motion={0};motion.type=SDL_EVENT_MOUSE_MOTION;motion.motion.xrel=4; + CHECK(SDL_PushEvent(&motion));Step(1);CHECK(player.angle==(angle+358)%360); + Event(SDL_EVENT_WINDOW_FOCUS_LOST);Step(1);CHECK(!IN_SDLCaptured() && !CT_Down(CT_FIRE)); + int32_t x=player.x;Key(SDL_SCANCODE_E,true);Step(1);CHECK(player.x==x); + Event(SDL_EVENT_WINDOW_FOCUS_GAINED);Step(1);CHECK(IN_SDLCaptured()); + Key(SDL_SCANCODE_E,true);Step(1);CHECK(player.x>x);Key(SDL_SCANCODE_E,false);Step(1); + CHECK(CT_Bind(CT_MENU,1,SDL_SCANCODE_P));Mouse(1,true);Tap(SDL_SCANCODE_P);Step(21);CHECK(DemoLoopState()==UI_MENU && !IN_SDLCaptured()); + uint32_t time=gamestate.TimeCount;Key(SDL_SCANCODE_E,true);Step(70);CHECK(gamestate.TimeCount==time); + MainItems.curpos=backtodemo;Tap(SDL_SCANCODE_RETURN);Step(21);CHECK(DemoLoopState()==UI_GAME && IN_SDLCaptured()); + CHECK(!CT_Down(CT_FIRE) && !CT_Down(CT_FORWARD)); + Mouse(1,false);Key(SDL_SCANCODE_E,false);Step(1);GameStop();CHECK(VW_UpdateScreen());CHECK(!IN_SDLCaptured());VL_Shutdown(); + puts("SDL controls menu, conflicts, relative capture, mouse/keys, focus and pause/resume passed."); +} +int main(int argc,char **argv) +{ + CHECK(argc==4);MM_Startup();CHECK(CA_Startup(argv[1]));CHECK(VL_SetPalette(gamepal,768));CHECK(Save_SetDirectory(argv[2])); + if(!strcmp(argv[3],"core")) Core();else SDLControls(); + GameStop();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes());return 0; +} diff --git a/tests/demo_trace.c b/tests/demo_trace.c new file mode 100644 index 00000000..7106c463 --- /dev/null +++ b/tests/demo_trace.c @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Developer-only deterministic trace harness; never linked into gameplay. */ +#include "engine/WL_DEF.h" +#include "engine/WL_DEMO.h" +#include "engine/WL_SAVE.h" +#include "engine/WL_RENDER.h" +#include "engine/ID_US_1.h" +#include "engine/ID_CA.h" +#include "engine/ID_VH.h" +#include +#include +#include +#define SAVE_STATE(name) #name, +static const char *const names[]={"null", +#include "engine/WL_SAVE_STATES.inc" +}; +#undef SAVE_STATE +static const char *State(const statetype *s) { unsigned id=Save_StateID(s);return idx,o->y,o->vertical?1U:0U,o->lock,(int)o->action,o->ticcount,(unsigned)o->position); + } + printf("Q"); + for(unsigned x=0;x<64;++x) for(unsigned y=0;y<64;++y) { + unsigned slot=0; + for(unsigned j=0;actorat[x][y] && jnext,++i) + printf("A,%u,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%u,%d,%d,%d\n",i,State(o->state),o->x,o->y,o->angle,o->tilex,o->tiley,o->obclass, + o->ticcount,o->hitpoints,o->dir,o->speed,o->distance,o->temp1,o->temp2,o->flags,o->active?1:0,o->viewx,o->viewheight); +} +int main(int argc,char **argv) +{ + bool high=argc==3 && !strcmp(argv[2],"--render"); + if(argc!=2 && !high) return 2; + w3r_byte *pixels=high?malloc(1920*1080):NULL; + wl_present_snapshot *snapshot=high?malloc(sizeof(*snapshot)):NULL; + if(high && (!pixels || !snapshot)) return 2; + MM_Startup();if(!CA_Startup(argv[1])) return 2; + for(unsigned n=0;n<4;++n) { + if(!NewViewSize(15) || !Demo_Start(n,0)) return 2; + Trace(n); + for(uint64_t t=4;!Demo_Finished();t+=4) { + if(!GameStep(t)) return 2; + if(high) { + demo_progress p;wl_render_target target;int32_t depth[1920]; + if(!Demo_Progress(&p)) return 2; + unsigned w=640,h=480; + if(p.commands_consumed%128==0) { w=1280;h=720; } + if(p.commands_consumed%256==0) { w=1920;h=1080; } + if(!WL_PresentSample(WL_TickNS(t)+7142857,snapshot) || !WL_TargetInit(&target,pixels,1920*1080,w,h,w) || !WL_RenderSnapshot(&target,depth,1920,true,(p.commands_consumed%5==0)?32U:16U,9,snapshot,NULL)) return 2; + } + Trace(n); + } + GameStop(); + } + free(snapshot);free(pixels);CA_Shutdown();MM_Shutdown();return MM_TotalBytes()?2:0; +} diff --git a/tests/demo_trace_tools.py b/tests/demo_trace_tools.py new file mode 100644 index 00000000..a677fee8 --- /dev/null +++ b/tests/demo_trace_tools.py @@ -0,0 +1,129 @@ +"""Stable, streaming native/DOS trace readers. No executable addresses in hashes.""" +# SPDX-License-Identifier: GPL-2.0-only +import csv +import hashlib +import json +from pathlib import Path +import re +import struct + +DOS_RECORD = 26251 + +def native_frames(path, include_initial=False): + frame = None + with Path(path).open(newline='') as stream: + for row in csv.reader(stream): + kind = row[0] + if kind == 'F': + if frame is not None and (include_initial or frame['F'][1]): + yield frame + frame = {'F': list(map(int, row[1:])), 'A': [], 'D': []} + elif frame is None: + raise ValueError('Trace row precedes frame header') + elif kind == 'A': + # Player is stepped directly in the port, rather than through + # DOS s_player/s_attack pointers. Its state is in the F fields. + if row[1] != '0': + frame['A'].append([int(row[1]), row[2], *map(int, row[3:])]) + elif kind in ('V', 'M'): + frame[kind] = row[1] + elif kind == 'Q': + frame[kind] = list(map(int, row[1:])) + elif kind == 'D': + frame[kind].append(list(map(int, row[1:]))) + else: + raise ValueError('Unknown trace row '+kind) + if frame is not None and (include_initial or frame['F'][1]): + yield frame + + +def dos_frames(path, symbol_map): + text = Path(symbol_map).read_text() + states = {int(address, 16): name for address, name in re.findall( + r'3A39:([0-9A-F]+)\s+(?:idle\s+)?_(s_\w+)', text)} + def short(data, offset): + return struct.unpack_from('= 0xb51c+9000: + raise ValueError('Invalid DOS actor list') + seen.add(pointer) + actor = actors[pointer-0xb51c:pointer-0xb51c+60] + state = word(actor, 6) + if state not in states: + raise ValueError('Unknown DOS actor state') + rows.append([len(rows), states[state], long(actor,16), long(actor,20), short(actor,42), + word(actor,24), word(actor,26), short(actor,4), short(actor,2), short(actor,44), + short(actor,14), long(actor,46), long(actor,10), short(actor,50), short(actor,52), + actor[8], int(short(actor,0) != 0), short(actor,30), word(actor,32)]) + pointer = word(actor,56) + if not rows: + raise ValueError('Missing DOS player') + command = struct.unpack_from(' 64: + raise ValueError('Invalid DOS door count') + doors = [] + for i in range(count): + door = data[17417+i*10:17427+i*10] + doors.append([i, door[0], door[1], word(door,2), door[4], + {0:2,1:0,2:1,3:3}[short(door,6)], word(door,8), word(data,17289+i*2)]) + grid = [] + for i in range(4096): + value = word(data,18057+i*2) + if value < 256: + grid.append(0) # Solid integer tags are represented by M/D. + elif 0xb51c <= value < 0xb51c+9000 and (value-0xb51c)%60 == 0: + grid.append((value-0xb51c)//60) + else: + raise ValueError('Invalid DOS reservation') + yield {'F': f, 'A': rows[1:], 'D': doors, 'Q': grid, + 'V': ''.join('1' if b else '0' for b in data[9097:13193]), + 'M': data[13193:17289].hex()} + + +def canonical(frame): + result = dict(frame) + # SpawnDoor does not initialise ticcount in DOS. The value has no meaning + # outside dr_open; DoorOpening resets it before the timer can be used. + result['D'] = [row[:6]+[row[6] if row[5] == 2 else 0, row[7]] for row in frame['D']] + return result + + +def digest(frame): + value = json.dumps(canonical(frame), sort_keys=True, separators=(',', ':')).encode() + return hashlib.sha256(value).hexdigest() + + +def compare(native, reference): + """Return first differing frame/component, or None for complete equality.""" + from itertools import zip_longest + for left, right in zip_longest(native, reference): + if left is None or right is None: + return {'frame': (left or right)['F'][:2], 'component': 'duration'} + a, b = canonical(left), canonical(right) + for key in ('F', 'A', 'V', 'M', 'Q', 'D'): + if a[key] != b[key]: + return {'frame': b['F'][:2], 'component': key, 'native': a[key], 'dos': b[key]} + return None diff --git a/tests/display_tests.c b/tests/display_tests.c new file mode 100644 index 00000000..e20d3652 --- /dev/null +++ b/tests/display_tests.c @@ -0,0 +1,252 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/ID_CA.h" +#include "engine/ID_IN.h" +#include "engine/ID_US_1.h" +#include "engine/ID_VL.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_MENU.h" +#include "engine/WL_SAVE.h" +#include "engine/WL_CONTROLS.h" +#include "engine/WL_DISPLAY.h" +#include "platform/sdl_input.h" +#include "platform/sdl_video.h" +#include +#include +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s; %s)\n",__LINE__,#x,SDL_GetError(),CA_Error());exit(1); } } while(0) +#include "finish_loading.h" +static SDL_Window *window; +static SDL_Renderer *renderer; +static uint64_t ticks; +static const int presets[][2]={ + {640,480},{960,720},{1280,960},{960,600},{1280,800},{1600,1000},{1920,1200}, + {960,540},{1280,720},{1600,900},{1920,1080},{1680,720},{2560,1080},{1920,540},{2560,720} +}; +static display_settings Settings(void) { display_settings s;CHECK(VL_DisplayGet(&s));return s; } +static void Pump(void) { CHECK(!VL_PollQuit());CHECK(VW_UpdateScreen()); } +static void AwaitDisplay(void) +{ + Uint64 until=SDL_GetTicks()+4000; + do { CHECK(SDL_SyncWindow(window));Pump();if(!Settings().pending) return;SDL_Delay(2); } while(SDL_GetTicks()0 && h>0); + int pw,ph;CHECK(SDL_GetWindowSizeInPixels(window,&pw,&ph));CHECK(w==pw && h==ph); + CHECK(SDL_GetWindowFlags(window)&SDL_WINDOW_HIGH_PIXEL_DENSITY); + SDL_FRect rect;CHECK(SDL_GetRenderLogicalPresentationRect(renderer,&rect)); + if(w<4 || h<3) continue; + double scale=fmin((double)w/320,(double)h/240); + if(mode && scale>=1) scale=floor(scale); + CHECK(fabs(rect.w-floor(320*scale))<=1 && fabs(rect.h-floor(240*scale))<=1); + CHECK(rect.x>=0 && rect.y>=0 && rect.x+rect.w<=w+1 && rect.y+rect.h<=h+1); + CHECK(fabs(rect.w*3-rect.h*4)<=4); /* At most a pixel of fit rounding. */ + /* Disable logical clipping only for full-output pixel readback. */ + SDL_RendererLogicalPresentation saved;int lw,lh;CHECK(SDL_GetRenderLogicalPresentation(renderer,&lw,&lh,&saved)); + CHECK(SDL_SetRenderLogicalPresentation(renderer,0,0,SDL_LOGICAL_PRESENTATION_DISABLED)); + SDL_Surface *surface=SDL_RenderReadPixels(renderer,NULL);CHECK(surface && surface->w==w && surface->h==h); + if(rect.x>=1) Pixel(surface,0,h/2,0,0,0); + if(rect.y>=1) Pixel(surface,w/2,0,0,0,0); + Pixel(surface,(int)(rect.x+rect.w/4),(int)(rect.y+rect.h/2),255,0,0); + Pixel(surface,(int)(rect.x+rect.w*3/4),(int)(rect.y+rect.h/2),0,255,0); + SDL_DestroySurface(surface);CHECK(SDL_SetRenderLogicalPresentation(renderer,lw,lh,saved)); + display_settings got=Settings();CHECK(got.pixel_width==w && got.pixel_height==h); + } + CHECK(VL_TextureUploads()==uploads);Resize(1000,600); + display_settings s=Settings();s.integer=false;Set(s); + Key(SDL_SCANCODE_F11,true,SDL_KMOD_NONE);Pump();CHECK(Settings().integer); + SDL_Event repeat={0};repeat.type=SDL_EVENT_KEY_DOWN;repeat.key.scancode=SDL_SCANCODE_F11;repeat.key.repeat=true; + CHECK(SDL_PushEvent(&repeat));Pump();CHECK(Settings().integer); + Key(SDL_SCANCODE_F11,false,SDL_KMOD_NONE);Pump(); + CHECK(Settings().integer && !IN_AnyPressed() && !CT_Down(CT_FIRE)); + Shortcut(false);CHECK(!Settings().integer); + CHECK(!CT_Bind(CT_FIRE,0,SDL_SCANCODE_F11)); + Shortcut(true);CHECK(Settings().fullscreen==((SDL_GetWindowFlags(window)&SDL_WINDOW_FULLSCREEN)!=0)); + CHECK(Settings().fullscreen && !CT_Down(CT_ALT) && !IN_AnyPressed() && !Keyboard[sc_Enter]); + Shortcut(true);s=Settings();CHECK(!s.fullscreen && s.width==1000 && s.height==600); + Key(SDL_SCANCODE_RALT,true,SDL_KMOD_RALT);Pump();CHECK(CT_Down(CT_ALT)); + Key(SDL_SCANCODE_RALT,false,SDL_KMOD_NONE);Pump();IN_ClearKeysDown(); + Key(SDL_SCANCODE_KP_ENTER,true,SDL_KMOD_RALT);Key(SDL_SCANCODE_KP_ENTER,false,SDL_KMOD_RALT); + Key(SDL_SCANCODE_RALT,false,SDL_KMOD_NONE);Pump();CHECK(Settings().fullscreen && !IN_AnyPressed());Shortcut(true); + if(SDL_MinimizeWindow(window)) { Pump();CHECK(SDL_RestoreWindow(window));Pump(); } + else CHECK(*SDL_GetError()); /* Dummy drivers need not implement minimize. */ + s=Settings();s.fullscreen=true;Set(s);s=Settings();s.scale=2;Set(s); + CHECK(Settings().fullscreen && Settings().width==640); + s=Settings();s.fullscreen=false;Set(s);CHECK(Settings().width==640 && Settings().height==480); + Resize(1000,600); + /* An OS/external change must not leave a stale application fullscreen bit. */ + CHECK(SDL_SetWindowFullscreen(window,true));CHECK(SDL_SyncWindow(window));Pump();CHECK(Settings().fullscreen); + Shortcut(true);CHECK(!Settings().fullscreen); + s=Settings();s.fullscreen=true;VL_TestDisplayFailure(1);CHECK(!VL_DisplaySet(&s));CHECK(!Settings().fullscreen && *Settings().error); + s=Settings();s.integer=true;VL_TestDisplayFailure(2);CHECK(!VL_DisplaySet(&s));CHECK(!Settings().integer); + s=Settings();s.scale=4;VL_TestDisplayFailure(3);CHECK(!VL_DisplaySet(&s));CHECK(Settings().width==1000); + s=Settings();s.fullscreen=true;VL_TestDisplayFailure(4);CHECK(VL_DisplaySet(&s) && Settings().pending); + VL_TestExpireDisplayRequest();Pump();CHECK(!Settings().pending && !Settings().fullscreen && *Settings().error); + s=Settings();s.fullscreen=s.integer=false;s.scale=3;Set(s);CHECK(!*Settings().error && Settings().width==960); + Event(SDL_EVENT_WINDOW_FOCUS_LOST);Pump();Shortcut(false);CHECK(!Settings().integer); + Event(SDL_EVENT_WINDOW_FOCUS_GAINED);Pump();Shortcut(false);CHECK(Settings().integer);Shortcut(false); + puts("Display geometry, black bars, scaling, tiny windows, fullscreen, shortcuts and failures passed."); +} +static void Step(unsigned n) +{ while(n--) { CHECK(!VL_PollQuit());CHECK(DemoLoop(++ticks));if(GameLoading()) TestFinishLoading(ticks);CHECK(VW_UpdateScreen()); } } +static void Tap(SDL_Scancode code) { Key(code,true,SDL_KMOD_NONE);Key(code,false,SDL_KMOD_NONE);Step(1);AwaitDisplay(); } +static void Capture(const char *name) +{ + const char *dir=getenv("WOLF3D_CAPTURE_DIR");if(!dir) return; + char p[4096];(void)snprintf(p,sizeof(p),"%s/%s.bmp",dir,name);CHECK(VL_Capture(p)); +} +static void Game(void) +{ + Display_Connect(VL_DisplayGet,VL_DisplaySet);CHECK(DemoLoopStartup(0,true));Step(11); + MainItems.curpos=control;Tap(SDL_SCANCODE_RETURN);Step(21); + /* Display is reachable directly from the original Control screen. */ + Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_RETURN);Step(21); + CHECK(DemoLoopState()==UI_DISPLAY); + Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_DOWN); /* Window size */ + for(unsigned direction=0;direction<2;++direction) for(unsigned i=1;i<=15;++i) { + Tap(direction?SDL_SCANCODE_LEFT:SDL_SCANCODE_RIGHT); + unsigned index=(1+(direction?15-i:i))%15; + CHECK(Settings().width==presets[index][0] && Settings().height==presets[index][1]); + CHECK(!Settings().high_resolution && !Settings().integer && Settings().aspect==0); + } + Resize(1001,601);Tap(SDL_SCANCODE_LEFT);CHECK(Settings().width==2560 && Settings().height==720); + Tap(SDL_SCANCODE_RIGHT);CHECK(Settings().width==640 && Settings().height==480); + Resize(1001,601);Tap(SDL_SCANCODE_RIGHT);CHECK(Settings().width==640 && Settings().height==480); + Tap(SDL_SCANCODE_RIGHT);CHECK(Settings().width==960 && Settings().height==720); + Tap(SDL_SCANCODE_ESCAPE);Step(21);CHECK(DemoLoopState()==UI_CONTROLS); + Tap(SDL_SCANCODE_UP);Tap(SDL_SCANCODE_RETURN); /* DOS Customize controls -> modern options. */ + for(unsigned n=0;n<6;++n) Tap(SDL_SCANCODE_DOWN); + Tap(SDL_SCANCODE_RETURN);Step(21);CHECK(DemoLoopState()==UI_DISPLAY);Capture("display-settings"); + Tap(SDL_SCANCODE_RETURN);CHECK(Settings().fullscreen);Tap(SDL_SCANCODE_RETURN);CHECK(!Settings().fullscreen); + Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_RETURN);CHECK(Settings().integer); + Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_RIGHT);CHECK(Settings().width==1280 && Settings().height==960); + Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_RETURN);CHECK(Settings().high_resolution); + Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_RIGHT);CHECK(Settings().render_width==1280); + Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_RETURN);CHECK(!Settings().integer && Settings().scale==3 && !Settings().high_resolution); + Tap(SDL_SCANCODE_ESCAPE);Step(21);CT_Reset(CT_MODERN);CHECK(DemoLoopStartGame(ticks));Step(11);CHECK(IN_SDLCaptured()); + display_settings native=Settings();native.high_resolution=true;native.aspect=2;Set(native);CHECK(IN_SDLCaptured()); + native.high_resolution=false;Set(native);CHECK(IN_SDLCaptured());native.high_resolution=true;Set(native);CHECK(IN_SDLCaptured()); + unsigned rng=US_RndIndex();uint32_t time=gamestate.TimeCount; + Shortcut(true);CHECK(IN_SDLCaptured() && US_RndIndex()==rng && gamestate.TimeCount==time); + Shortcut(true);CHECK(IN_SDLCaptured() && !CT_Down(CT_ALT) && !CT_Down(CT_FIRE)); + Shortcut(false);CHECK(IN_SDLCaptured());Shortcut(false); + Event(SDL_EVENT_WINDOW_FOCUS_LOST);Pump();CHECK(!IN_SDLCaptured()); + Event(SDL_EVENT_WINDOW_FOCUS_GAINED);Pump();CHECK(IN_SDLCaptured()); + Tap(SDL_SCANCODE_ESCAPE);Step(21);CHECK(!IN_SDLCaptured()); + MainItems.curpos=control;Tap(SDL_SCANCODE_RETURN);Step(21); + Tap(SDL_SCANCODE_DOWN);if(CT_MouseEnabled()) Tap(SDL_SCANCODE_DOWN); + Tap(SDL_SCANCODE_RETURN); /* DOS Customize controls -> modern options. */ + for(unsigned n=0;n<6;++n) Tap(SDL_SCANCODE_DOWN); + Tap(SDL_SCANCODE_RETURN);Step(21);CHECK(DemoLoopState()==UI_DISPLAY); + time=gamestate.TimeCount;Step(70);CHECK(gamestate.TimeCount==time); + Tap(SDL_SCANCODE_ESCAPE);Step(21);Tap(SDL_SCANCODE_ESCAPE);Step(21);Tap(SDL_SCANCODE_ESCAPE);Step(21);MainItems.curpos=backtodemo;Tap(SDL_SCANCODE_RETURN);Step(21);CHECK(IN_SDLCaptured()); + GameStop();Display_Connect(NULL,NULL); + CT_Reset(CT_CLASSIC); + for(unsigned variant=0;variant<2;++variant) { + CHECK(GameStart(0)); + for(unsigned t=1;t<=60;++t) { + if(variant && t%10==0) { Shortcut(false);Resize(t%20?1000:960,t%20?600:720); } + IN_KeyEvent(sc_UpArrow,t<20);IN_KeyEvent(sc_RightArrow,t%13<4);CHECK(GameStep(t)); + } + CHECK(Save_Write(variant,variant?"display changes":"continuous",true)); + } + display_settings before=Settings();CHECK(Save_Load(0,60));display_settings after=Settings(); + CHECK(before.fullscreen==after.fullscreen && before.integer==after.integer && before.width==after.width); + puts("Display menu, capture/focus, pause/resume, simulation/RNG and save compatibility passed."); +} +/* Watch SDL's window events as well as dimensions: even a transient resize + during a menu transition violates window/presentation independence. */ +static unsigned resize_events; +static bool SDLCALL WatchResize(void *unused,SDL_Event *event) +{ + (void)unused; + if(event->type==SDL_EVENT_WINDOW_RESIZED || event->type==SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED) ++resize_events; + return true; +} +static void Canvas(bool world,unsigned ratio) +{ + int lw,lh,w,h;SDL_RendererLogicalPresentation mode; + CHECK(SDL_GetRenderLogicalPresentation(renderer,&lw,&lh,&mode)); + CHECK(SDL_GetRenderOutputSize(renderer,&w,&h)); + if(!world) { + CHECK(lw==320 && lh==240); + CHECK(mode==SDL_LOGICAL_PRESENTATION_INTEGER_SCALE); + } else { + static const double ratios[]={0,4.0/3,16.0/9,16.0/10,21.0/9,32.0/9}; + double expected=ratio?ratios[ratio]:fmax(4.0/3,fmin(32.0/9,(double)w/h)); + CHECK(fabs((double)lw/lh-expected)<0.02); + CHECK(mode==SDL_LOGICAL_PRESENTATION_LETTERBOX); + SDL_FRect rect;CHECK(SDL_GetRenderLogicalPresentationRect(renderer,&rect)); + CHECK(fabs((double)rect.w-w)<=2 || fabs((double)rect.h-h)<=2); + } +} +static void Transitions(void) +{ + Display_Connect(VL_DisplayGet,VL_DisplaySet);CHECK(DemoLoopStartup(0,true));Step(11); + CHECK(DemoLoopStartGame(ticks));Step(11); + const int sizes[][3]={{960,720,1},{960,540,2},{960,600,3},{1680,720,4},{2560,720,5},{1001,601,3}}; + CHECK(SDL_AddEventWatch(WatchResize,NULL)); + for(unsigned i=0;i<6;++i) for(unsigned automatic=0;automatic<2;++automatic) { + display_settings d=Settings();d.scale=0;d.width=sizes[i][0];d.height=sizes[i][1]; + d.high_resolution=d.integer=true;d.aspect=automatic?0:(unsigned)sizes[i][2];Set(d); + CHECK(SDL_SyncWindow(window));Pump(); + int w,h;CHECK(SDL_GetWindowSize(window,&w,&h)); + printf("Transition window requested %dx%d, actual %dx%d, aspect %u\n",d.width,d.height,w,h,d.aspect); + /* WM limits may clamp native windows. Dummy SDL must apply exactly. */ + if(!strcmp(SDL_GetCurrentVideoDriver(),"dummy")) CHECK(w==d.width && h==d.height); + Canvas(true,d.aspect);resize_events=0; + Tap(SDL_SCANCODE_ESCAPE);Step(21);CHECK(DemoLoopState()==UI_MENU);Canvas(false,0); + MainItems.curpos=control;Tap(SDL_SCANCODE_RETURN);Step(21);CHECK(DemoLoopState()==UI_CONTROLS);Canvas(false,0); + Tap(SDL_SCANCODE_UP);Tap(SDL_SCANCODE_RETURN);Step(21);CHECK(DemoLoopState()==UI_DISPLAY);Canvas(false,0); + Tap(SDL_SCANCODE_ESCAPE);Step(21);CHECK(DemoLoopState()==UI_CONTROLS); + Tap(SDL_SCANCODE_ESCAPE);Step(21);CHECK(DemoLoopState()==UI_MENU); + MainItems.curpos=backtodemo;Tap(SDL_SCANCODE_RETURN);Step(21);CHECK(DemoLoopState()==UI_GAME);Canvas(true,d.aspect); + int after_w,after_h;CHECK(SDL_GetWindowSize(window,&after_w,&after_h)); + CHECK(w==after_w && h==after_h && resize_events==0); + d=Settings();CHECK(d.width==w && d.height==h && d.integer && d.high_resolution); + /* Fullscreen keeps the independent windowed dimensions and settings. */ + d.fullscreen=true;Set(d);CHECK(Settings().width==w && Settings().height==h); + d=Settings();d.fullscreen=false;Set(d);CHECK(Settings().width==w && Settings().height==h); + Resize(w-1,h-1);CHECK(Settings().width==w-1 && Settings().height==h-1); + } + SDL_RemoveEventWatch(WatchResize,NULL);GameStop();Display_Connect(NULL,NULL); + puts("All aspects, Auto, menu integer scaling, resize-free transitions, manual resize and fullscreen restoration passed."); +} +int main(int argc,char **argv) +{ + CHECK(argc==4);MM_Startup();CHECK(VL_Startup()); + int n;SDL_Window **windows=SDL_GetWindows(&n);CHECK(windows && n==1);window=windows[0];SDL_free(windows);renderer=SDL_GetRenderer(window);CHECK(renderer); + if(!strcmp(argv[3],"geometry")) Geometry(); + else { CHECK(CA_Startup(argv[1]));CHECK(VL_SetPalette(gamepal,768));CHECK(Save_SetDirectory(argv[2]));if(!strcmp(argv[3],"transitions")) Transitions();else Game();GameStop();CA_Shutdown(); } + VL_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes());return 0; +} diff --git a/tests/dos_menu_tests.c b/tests/dos_menu_tests.c new file mode 100644 index 00000000..c5e1b359 --- /dev/null +++ b/tests/dos_menu_tests.c @@ -0,0 +1,214 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Independent source-composition oracle; all graphics are loaded at runtime. */ +#include "engine/WL_MENU.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_CONTROLS.h" +#include "engine/WL_DISPLAY.h" +#include "engine/WL_SAVE.h" +#include "engine/ID_CA.h" +#include "engine/ID_VL.h" +#include "engine/ID_IN.h" +#include "engine/ID_SD.h" +#include "engine/ID_US_1.h" +#include "platform/sdl_video.h" +#include "platform/config_file.h" +#include +#include +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s / %s)\n",__LINE__,#x,CA_Error(),SDL_GetError());exit(1); } } while(0) +#include "finish_loading.h" +static unsigned char expected[64000]; +static void Key(unsigned scan) { IN_KeyEvent(scan,true);IN_KeyEvent(scan,false); } +static void Control(unsigned scan) { Key(scan);CHECK(HandleControlsMenu()==0); } +static void Sound(unsigned scan) { Key(scan);CHECK(HandleSoundSettings()==0); } +static unsigned LE16(const unsigned char *p) { return p[0]+256U*p[1]; } +static void Bar(int x,int y,int w,int h,unsigned char color) +{ for(int row=y;row0); + FILE *f=fopen(path,"wb");CHECK(f && fwrite(framebuffer,1,64000,f)==64000 && fclose(f)==0); + CHECK(snprintf(path,sizeof(path),"%s/palette.bin",dir)>0);f=fopen(path,"wb"); + CHECK(f && fwrite(gamepal,1,768,f)==768 && fclose(f)==0); +} +static void Menus(const char *directory) +{ + CHECK(SetupControlPanel(0));Capture(directory,"main"); + CT_Reset(CT_CLASSIC);ResetMenuCursor(0);CHECK(BeginControlsMenu());ControlOracle(0,false,C_CURSOR1PIC);Capture(directory,"control-off"); + IN_KeyEvent(sc_DownArrow,true);CHECK(HandleControlsMenu()==0);ControlOracle(5,false,C_CURSOR1PIC); + (void)TickMenuCursor(19);CHECK(HandleControlsMenu()==0);ControlOracle(5,false,C_CURSOR1PIC); + (void)TickMenuCursor(20);CHECK(HandleControlsMenu()==0);ControlOracle(6,false,C_CURSOR1PIC); + IN_KeyEvent(sc_DownArrow,false);Control(sc_UpArrow);ControlOracle(5,false,C_CURSOR1PIC); + Control(sc_UpArrow);ControlOracle(0,false,C_CURSOR1PIC); + Control(sc_Enter);ControlOracle(0,true,C_CURSOR1PIC); + Control(sc_DownArrow);ControlOracle(4,true,C_CURSOR1PIC);Control(sc_Enter); + unsigned sensitivity=CT_Sensitivity();Control(sc_RightArrow);CHECK(CT_Sensitivity()==sensitivity+1); + Control(sc_Escape);Control(sc_DownArrow);Control(sc_Enter);Capture(directory,"customize"); + Control(sc_Enter);CHECK(CT_Preset()==CT_MODERN); + for(unsigned i=0;i<3;++i) Control(sc_DownArrow); + Control(sc_Enter);CHECK(CT_Invert()); + Key(sc_Escape);CHECK(HandleControlsMenu()==0);ControlOracle(5,CT_MouseEnabled(),C_CURSOR1PIC); + CHECK(BeginControlsMenu());ResetMenuCursor(0);CHECK(!TickMenuCursor(8));CHECK(TickMenuCursor(9)); + CHECK(DrawControlsMenu());ControlOracle(0,true,C_CURSOR2PIC); + CHECK(TickMenuCursor(18));CHECK(DrawControlsMenu());ControlOracle(0,true,C_CURSOR1PIC);Capture(directory,"control-on"); + unsigned char fine[64000];for(uint64_t t=19;t<1000;++t) (void)TickMenuCursor(t); + CHECK(DrawControlsMenu());memcpy(fine,framebuffer,sizeof(fine)); + ResetMenuCursor(0);CHECK(TickMenuCursor(999));CHECK(DrawControlsMenu());CHECK(!memcmp(fine,framebuffer,sizeof(fine))); + SD_SetEnabled(true,true);SD_SetDigitizedMode(true);CHECK(BeginSoundSettings());Capture(directory,"sound"); + SoundOracle(); + Sound(sc_Enter);unsigned m,e;bool mon,eon;SD_GetSettings(&m,&e,&mon,&eon);CHECK(mon && !eon); + Sound(sc_DownArrow);Sound(sc_Enter);Sound(sc_DownArrow);Sound(sc_Enter);Capture(directory,"volumes"); + SD_SetVolumes(70,85);Sound(sc_LeftArrow);Sound(sc_DownArrow);Sound(sc_RightArrow); + SD_GetSettings(&m,&e,&mon,&eon);CHECK(m==65 && e==90); + Sound(sc_Escape);Sound(sc_DownArrow);Sound(sc_Enter);SD_GetSettings(&m,&e,&mon,&eon);CHECK(!mon && eon); + CHECK(Config_Save(directory));CT_Reset(CT_CLASSIC);SD_SetEnabled(true,false);SD_SetVolumes(0,0); + CHECK(Config_Load(directory)==CONFIG_LOADED && CT_Preset()==CT_MODERN && CT_Invert()); + SD_GetSettings(&m,&e,&mon,&eon);CHECK(m==65 && e==90 && !mon && eon); + CT_SelectPreset(CT_CLASSIC);CHECK(CT_Sensitivity()==sensitivity+1 && CT_MouseEnabled()); + CT_SelectPreset(CT_MODERN); +} +static SDL_Renderer *renderer; +static void Geometry(int w,int h) +{ + display_settings d;CHECK(VL_DisplayGet(&d));d.scale=0;d.width=w;d.height=h;d.integer=false; + CHECK(VL_DisplaySet(&d) && !VL_PollQuit() && VW_UpdateScreen()); + SDL_FRect rect;CHECK(SDL_GetRenderLogicalPresentationRect(renderer,&rect)); + double expected_w=h*4.0/3.0,expected_h=h; + if(expected_w>w) { expected_w=w;expected_h=w*3.0/4.0; } + CHECK(fabs(rect.w-expected_w)<=1 && fabs(rect.h-expected_h)<=1); + CHECK(fabs(rect.x-(w-expected_w)/2)<=1 && fabs(rect.y-(h-expected_h)/2)<=1); + int lw,lh;SDL_RendererLogicalPresentation mode;CHECK(SDL_GetRenderLogicalPresentation(renderer,&lw,&lh,&mode)); + CHECK(lw==320 && lh==240 && mode==SDL_LOGICAL_PRESENTATION_LETTERBOX); + if(w==1920 && h==1200) CHECK(rect.x==160 && rect.y==0 && rect.w==1600 && rect.h==1200); + CHECK(SDL_SetRenderLogicalPresentation(renderer,0,0,SDL_LOGICAL_PRESENTATION_DISABLED)); + SDL_Surface *surface=SDL_RenderReadPixels(renderer,NULL);CHECK(surface && surface->w==w && surface->h==h); + if(rect.x>=1) for(unsigned side=0;side<2;++side) { + Uint8 r,g,b,a;CHECK(SDL_ReadSurfacePixel(surface,side?w-1:0,h/2,&r,&g,&b,&a)); + CHECK(r==0 && g==0 && b==0 && a==255); + } + SDL_DestroySurface(surface);CHECK(SDL_SetRenderLogicalPresentation(renderer,lw,lh,mode)); +} +static void Presentation(const char *directory) +{ + CHECK(DemoLoopStartup(0,true));CHECK(DemoLoopStartGame(0));CHECK(DemoLoop(11));TestFinishLoading(11); + display_settings d;CHECK(VL_DisplayGet(&d));d.high_resolution=true;d.render_width=1280;d.render_height=720;d.aspect=2; + CHECK(VL_DisplaySet(&d) && VW_UpdateScreen()); + unsigned rng=US_RndIndex();uint32_t clock=gamestate.TimeCount; + CHECK(Save_Write(0,"before menus",true)); + Key(sc_Escape);CHECK(DemoLoop(12) && DemoLoop(32));CHECK(DemoLoopState()==UI_MENU); + const int sizes[][2]={{1920,1200},{1920,1080},{3440,1440},{3840,1080}}; + for(unsigned n=0;n<4;++n) { + Geometry(sizes[n][0],sizes[n][1]); + MainItems.curpos=control;Key(sc_Enter);CHECK(DemoLoop(33+n*50) && DemoLoop(53+n*50)); + CHECK(DemoLoopState()==UI_CONTROLS);CHECK(VW_UpdateScreen());Geometry(sizes[n][0],sizes[n][1]); + Key(sc_Escape);CHECK(DemoLoop(54+n*50) && DemoLoop(74+n*50));CHECK(DemoLoopState()==UI_MENU); + } + MainMenu[soundmenu].active=1;MainItems.curpos=soundmenu;Key(sc_Enter); + CHECK(DemoLoop(225) && DemoLoop(245) && DemoLoopState()==UI_SOUND);Geometry(1920,1200); + Key(sc_Escape);CHECK(DemoLoop(246) && DemoLoop(266) && DemoLoopState()==UI_MENU); + CHECK(US_RndIndex()==rng && gamestate.TimeCount==clock && Save_Write(1,"after menus",true)); + CHECK(!VL_PollQuit());CHECK(VL_DisplayGet(&d));d.fullscreen=true;CHECK(VL_DisplaySet(&d)); + CHECK(!VL_PollQuit() && VW_UpdateScreen());CHECK(VL_DisplayGet(&d) && d.fullscreen);d.fullscreen=false; + CHECK(VL_DisplaySet(&d) && !VL_PollQuit() && VW_UpdateScreen());Geometry(1920,1200); + MainItems.curpos=backtodemo;Key(sc_Enter);CHECK(DemoLoop(300) && DemoLoop(320));CHECK(DemoLoopState()==UI_GAME); + CHECK(VW_UpdateScreen());SDL_FRect rect;CHECK(SDL_GetRenderLogicalPresentationRect(renderer,&rect));CHECK(fabs(rect.w/rect.h-16.0/9)<0.002); + GameStop();CHECK(DemoLoopStartup(0,false));bool available=CA_GrChunkPresent(PG13PIC); + if(available) { + unsigned width=pictable[PG13PIC-STARTPICS].width; + pictable[PG13PIC-STARTPICS].width=80; + CHECK(DemoLoopIntro(0) && DemoLoopState()==UI_TITLE); + pictable[PG13PIC-STARTPICS].width=(w3r_word)width; + } + CHECK(DemoLoopIntro(0)); + if(available) { + CHECK(DemoLoopState()==UI_RATING);memset(expected,0x82,sizeof(expected));Pic(216,110,PG13PIC); + CHECK(!memcmp(expected,framebuffer,sizeof(expected)));Capture(directory,"pg13");Geometry(1920,1200); + CHECK(DemoLoop(30) && DemoLoop(519));CHECK(DemoLoopState()==UI_RATING); + CHECK(DemoLoop(520) && DemoLoop(550) && DemoLoopState()==UI_TITLE); + CHECK(DemoLoopStartup(0,false) && DemoLoopIntro(0) && DemoLoop(30));Key(sc_Space); + CHECK(DemoLoop(31) && DemoLoop(61) && DemoLoopState()==UI_TITLE); + } else CHECK(DemoLoopState()==UI_TITLE); + CHECK(DemoLoopStartup(0,false));CHECK(CA_CacheScreen(TITLEPIC));Capture(directory,"title");Geometry(1920,1200); + CHECK(CA_CacheScreen(CREDITSPIC));Capture(directory,"credits");Geometry(3440,1440); +} +static void StaticGameScreens(void) +{ + CHECK(DemoLoopStartGame(1000) && DemoLoop(1011)); + playstate=ex_completed;CHECK(GameStep(1012) && GameIntermission()); + uint32_t clock=gamestate.TimeCount;unsigned rng=US_RndIndex(); + unsigned char frame[64000];memcpy(frame,framebuffer,sizeof(frame)); + Geometry(1920,1200);CHECK(!memcmp(frame,framebuffer,sizeof(frame))); + CHECK(gamestate.TimeCount==clock && US_RndIndex()==rng); + CHECK(DemoLoopStartGame(1100) && DemoLoop(1111)); + playstate=ex_victorious;CHECK(GameStep(1112) && GameVictoryPresentation()); + Geometry(1920,1200);Key(sc_Enter);CHECK(GameStep(1113)); + CHECK(GameVictoryPresentation());memcpy(frame,framebuffer,sizeof(frame)); + clock=gamestate.TimeCount;rng=US_RndIndex();Geometry(3440,1440); + CHECK(!memcmp(frame,framebuffer,sizeof(frame)) && gamestate.TimeCount==clock && US_RndIndex()==rng); + CHECK(DemoLoopStartGame(1200) && DemoLoop(1211));TestFinishLoading(1211);CHECK(VW_UpdateScreen()); + SDL_FRect rect;CHECK(SDL_GetRenderLogicalPresentationRect(renderer,&rect)); + CHECK(fabs(rect.w/rect.h-16.0/9)<0.002); +} +int main(int argc,char **argv) +{ + CHECK(argc==3);MM_Startup();CHECK(CA_Startup(argv[1]) && VL_SetPalette(gamepal,768) && VL_Startup()); + int n;SDL_Window **windows=SDL_GetWindows(&n);CHECK(windows && n==1);renderer=SDL_GetRenderer(windows[0]);SDL_free(windows); + Display_Connect(VL_DisplayGet,VL_DisplaySet);CHECK(Save_SetDirectory(argv[2]));Menus(argv[2]);Presentation(argv[2]);StaticGameScreens(); + Display_Connect(NULL,NULL);GameStop();VL_Shutdown();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); + puts("DOS control composition, cursor, supported sound, persistence, intro, 4:3 menus and widescreen return passed.");return 0; +} diff --git a/tests/dos_ui_reference.c b/tests/dos_ui_reference.c new file mode 100644 index 00000000..6945fa6e --- /dev/null +++ b/tests/dos_ui_reference.c @@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_MENU.h" +#include "engine/ID_CA.h" +#include "engine/ID_VH.h" +#include "engine/WL_DEF.h" +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s)\n",__LINE__,#x,CA_Error());exit(1); } } while(0) +static unsigned char planes[64000]; +static void Compare(FILE *f,unsigned index) +{ + CHECK(fread(planes,1,sizeof(planes),f)==sizeof(planes)); + unsigned differences=0; + for(unsigned y=0;y<200;++y) for(unsigned x=0;x<320;++x) + if(framebuffer[y*320+x]!=planes[(x%4)*16000+y*80+x/4]) ++differences; + if(differences) { fprintf(stderr,"DOS UI frame %u: %u differing pixels\n",index,differences);exit(1); } +} +int main(int argc,char **argv) +{ + CHECK(argc==3);MM_Startup();CHECK(CA_Startup(argv[1])); + FILE *f=fopen(argv[2],"rb");CHECK(f); + for(unsigned i=0;i<18;++i) { + unsigned n=i%9;ClearMScreen(); + CHECK(MessageAtHeight(MenuQuitMessage(n,n==8?1:0),i<9?200U:160U));Compare(f,i); + } + for(unsigned i=0;i<2;++i) { ClearMScreen();CHECK(DrawSaveActivity(i!=0,false));Compare(f,18+i); } + ClearMScreen();CHECK(VWB_DrawPic(48,56,GETPSYCHEDPIC));Compare(f,20); + for(unsigned i=0;i<=5;++i) { PreloadUpdate(i,5);Compare(f,21+i); } + ClearMScreen();CHECK(VWB_DrawPic(128,64,PAUSEDPIC));Compare(f,27); + CHECK(MessageAtHeight("You are currently in\na game. Continuing will\nerase old game. Ok?",200));Compare(f,28); + CHECK(DrawHighScores());Compare(f,29); + CHECK(fgetc(f)==EOF && fclose(f)==0);CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); + puts("30 DOS frames match: quit/disk dialogs, Get Psyched artwork and six progress stages, Pause artwork, new-game message and default scores.");return 0; +} diff --git a/tests/engine_tests.c b/tests/engine_tests.c new file mode 100644 index 00000000..0369b49a --- /dev/null +++ b/tests/engine_tests.c @@ -0,0 +1,159 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/ID_CA.h" +#include "engine/ID_VL.h" +#include +#include +#include + +#define CHECK(x) do { if (!(x)) { fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__, #x, CA_Error()); exit(1); } } while (0) + +static void TestMemory(void) +{ + memptr a = NULL, b = NULL, foreign = NULL; + MM_Startup(); + CHECK(!MM_GetPtr(NULL, 4)); + CHECK(!MM_GetPtr(&a, 0)); + CHECK(!MM_GetPtr(&a, SIZE_MAX)); + CHECK(!MM_GetPtr(&a, MM_MAX_BYTES + 1)); + CHECK(!a && !MM_TotalBytes()); + CHECK(MM_GetPtr(&a, 8)); + CHECK(MM_GetPtr(&b, 16)); + for (size_t i = 0; i < 8; ++i) CHECK(((w3r_byte *)a)[i] == 0); + CHECK(!MM_GetPtr(&a, 4)); + CHECK(MM_TotalBytes() == 24); + CHECK(!MM_FreePtr(&foreign)); + CHECK(!MM_SetPurge(&a, 4)); + CHECK(MM_SetPurge(&a, 3)); + CHECK(MM_SetLock(&a, true)); + MM_SortMem(); + CHECK(a && b && MM_TotalBytes() == 24); + CHECK(MM_SetLock(&a, false)); + MM_SortMem(); + CHECK(!a && b && MM_TotalBytes() == 16); + CHECK(MM_FreePtr(&b)); + CHECK(!MM_FreePtr(&b)); + CHECK(!MM_TotalBytes()); + CHECK(MM_GetPtr(&a, 1)); + MM_Shutdown(); + CHECK(!a && !MM_TotalBytes()); + MM_Shutdown(); +} + +static void TestHuffman(void) +{ + huffnode table[255] = {{0, 0}}; + w3r_byte source = 0xa6, out[10]; + memset(out, 0xcc, sizeof(out)); + table[254].bit0 = 'A'; table[254].bit1 = 'B'; + CHECK(CAL_ValidateHuffman(table)); + CHECK(CAL_HuffExpand(&source, 1, out, 8, table)); + CHECK(memcmp(out, "ABBAABAB", 8) == 0 && out[8] == 0xcc); + CHECK(!CAL_HuffExpand(&source, 1, out, 9, table)); + CHECK(out[9] == 0xcc); + CHECK(!CAL_HuffExpand(&source, 0, out, 1, table)); + CHECK(!CAL_HuffExpand(NULL, 1, out, 1, table)); + CHECK(!CAL_HuffExpand(&source, 1, NULL, 1, table)); + CHECK(CAL_HuffExpand(NULL, 0, NULL, 0, table)); + table[254].bit0 = 256; table[0].bit0 = 'C'; table[0].bit1 = 'D'; + source = 0x18; + CHECK(CAL_HuffExpand(&source, 1, out, 4, table)); + CHECK(memcmp(out, "CDBC", 4) == 0); + table[254].bit0 = 511; + CHECK(!CAL_ValidateHuffman(table)); + CHECK(!CAL_HuffExpand(&source, 1, out, 1, table)); + table[254].bit0 = 510; source = 0; /* Cycle back to the root. */ + CHECK(!CAL_ValidateHuffman(table)); + CHECK(!CAL_HuffExpand(&source, 1, out, 1, table)); + /* Deterministic malformed-tree/stream corpus, bounded output with canaries. */ + uint32_t random = 0x12345678; + for (unsigned iteration = 0; iteration < 2000; ++iteration) { + for (size_t i = 0; i < 255; ++i) { + random = random * UINT32_C(1664525) + UINT32_C(1013904223); + table[i].bit0 = (uint16_t)(random & 1023); + table[i].bit1 = (uint16_t)((random >> 10) & 1023); + } + w3r_byte guarded[34], bits[8]; + memset(guarded, 0xc7, sizeof(guarded)); + for (size_t i = 0; i < sizeof(bits); ++i) bits[i] = (w3r_byte)(random >> (i % 4)); + (void)CAL_HuffExpand(bits, sizeof(bits), guarded + 1, 32, table); + CHECK(guarded[0] == 0xc7 && guarded[33] == 0xc7); + } +} + +static void TestVideoBuffers(void) +{ + const w3r_byte planes[16] = {0,4,8,12, 1,5,9,13, 2,6,10,14, 3,7,11,15}; + static w3r_byte rgba[VL_PIXELS * 4]; + w3r_byte invalid[768]; + memset(framebuffer, 0xee, VL_PIXELS); + CHECK(VL_MemToScreen(planes, sizeof(planes), 8, 2, 3, 4)); + for (size_t row = 0; row < 2; ++row) + for (size_t x = 0; x < 8; ++x) + CHECK(framebuffer[(row + 4) * 320 + x + 3] == row * 8 + x); + CHECK(framebuffer[4 * 320 + 2] == 0xee && framebuffer[4 * 320 + 11] == 0xee); + CHECK(!VL_MemToScreen(planes, 15, 8, 2, 0, 0)); + CHECK(!VL_MemToScreen(planes, 16, 7, 2, 0, 0)); + CHECK(!VL_MemToScreen(planes, 16, 8, 2, -1, 0)); + CHECK(!VL_MemToScreen(planes, 16, 8, 2, 313, 0)); + CHECK(!VL_MemToScreen(planes, 16, 8, 2, 0, 199)); + CHECK(!VL_MemToScreen(NULL, 16, 8, 2, 0, 0)); + CHECK(framebuffer[0] == 0xee); /* Failures must not partially write. */ + CHECK(VL_SetPalette(gamepal, sizeof(gamepal))); + memcpy(invalid, gamepal, sizeof(invalid)); invalid[7] = 64; + CHECK(!VL_SetPalette(invalid, sizeof(invalid))); + CHECK(!VL_SetPalette(gamepal, 767)); + CHECK(memcmp(palette, gamepal, sizeof(palette)) == 0); + for (size_t i = 0; i < VL_PIXELS; ++i) framebuffer[i] = (w3r_byte)(i % 256); + CHECK(VL_ConvertRGBA(rgba, sizeof(rgba))); + CHECK(!VL_ConvertRGBA(rgba, sizeof(rgba) - 1)); + for (size_t i = 0; i < VL_PIXELS; ++i) { + for (size_t channel = 0; channel < 3; ++channel) { + unsigned dac = gamepal[(i % 256) * 3 + channel]; + CHECK(rgba[i * 4 + channel] == (dac * 4 + dac / 16)); + } + CHECK(rgba[i * 4 + 3] == 255); + } + CHECK(gamepal[0] == 0 && gamepal[3] == 0 && gamepal[5] == 42); +} + +static void TestAssets(const char *directory, const char *dump) +{ + static w3r_byte rgba[VL_PIXELS * 4]; + MM_Startup(); + CHECK(CA_Startup(directory)); + CHECK(VL_SetPalette(gamepal, sizeof(gamepal))); + CHECK(CA_CacheScreen(TITLEPIC)); + CHECK(grsizes[TITLEPIC] == VL_PIXELS); + memptr cached = grsegs[TITLEPIC]; + size_t used = MM_TotalBytes(); + CHECK(CA_CacheGrChunk(TITLEPIC) && grsegs[TITLEPIC] == cached && MM_TotalBytes() == used); + CHECK(!CA_CacheGrChunk(-1) && !CA_CacheGrChunk(NUMCHUNKS)); + CHECK(!CA_CacheScreen(STARTFONT)); + CHECK(MM_SetPurge(&grsegs[TITLEPIC], 3) && MM_SetLock(&grsegs[TITLEPIC], true)); + MM_SortMem(); + CHECK(grsegs[TITLEPIC] == cached); + CHECK(MM_SetLock(&grsegs[TITLEPIC], false)); + MM_SortMem(); + CHECK(!grsegs[TITLEPIC]); + CHECK(CA_CacheScreen(TITLEPIC)); + CHECK(MM_TotalBytes() == used); + CHECK(VL_ConvertRGBA(rgba, sizeof(rgba))); + FILE *file = fopen(dump, "wb"); + CHECK(file); + CHECK(fwrite(framebuffer, 1, VL_PIXELS, file) == VL_PIXELS); + CHECK(fwrite(rgba, 1, sizeof(rgba), file) == sizeof(rgba)); + CHECK(fclose(file) == 0); + CA_Shutdown(); + CHECK(MM_TotalBytes() == 0); + CHECK(CA_Startup(directory)); /* Repeated lifecycle is clean. */ + CA_Shutdown(); MM_Shutdown(); + CHECK(!MM_TotalBytes()); +} + +int main(int argc, char **argv) +{ + TestMemory(); TestHuffman(); TestVideoBuffers(); + if (argc == 3) TestAssets(argv[1], argv[2]); + puts("Engine memory, Huffman, framebuffer/palette and cache tests passed."); + return 0; +} diff --git a/tests/finale_sdl_tests.c b/tests/finale_sdl_tests.c new file mode 100644 index 00000000..7b07ebba --- /dev/null +++ b/tests/finale_sdl_tests.c @@ -0,0 +1,139 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Controlled original-weapon fights and finale flows, not navigated episodes. + Owned files are read in place. Positions, ammo and health are controlled. */ +#include "engine/WL_DEF.h" +#include "engine/WL_MAIN.h" +#include "engine/ID_CA.h" +#include "engine/ID_IN.h" +#include "platform/sdl_video.h" +#include "platform/sdl_audio.h" +#include "engine/ID_SD.h" +#include +#include +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%d: %s (%s; %s)\n",__LINE__,#x,CA_Error(),VL_Error());exit(1); } } while (0) +#include "finish_loading.h" +static uint64_t ticks; +static unsigned ep; +static void Step(void) +{ + CHECK(!VL_PollQuit());CHECK(DemoLoop(++ticks));if(GameLoading()) TestFinishLoading(ticks);Audio_Pump();CHECK(VW_UpdateScreen()); + CHECK(DemoLoopState()!=UI_ERROR); +} +static void Steps(unsigned count) { while (count--) Step(); } +static void Key(SDL_Scancode scan,bool down) +{ + SDL_Event e={0};e.type=down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP;e.key.scancode=scan; + CHECK(SDL_PushEvent(&e)); +} +static void Tap(SDL_Scancode scan) { Key(scan,true);Key(scan,false);Step(); } +static objtype *Find(int kind) +{ + for (objtype *ob=player.next;ob;ob=ob->next) + if (ob->obclass==kind && (ob->flags&FL_SHOOTABLE)) return ob; + return NULL; +} +static void Aim(objtype *ob) +{ + double a=atan2((double)player.y-ob->y,(double)ob->x-player.x); + if (a<0) a+=6.28318530717958647692; + player.angle=(int)(a*360/6.28318530717958647692); +} +static void Arrange(objtype *ob) +{ + for (unsigned i=0;itilex)<10 && abs((int)doorobjlist[i].y-ob->tiley)<10) OpenDoor(i); + for (unsigned i=0;i<70;++i) MoveDoors(); + bool found=false; + for (int d=2;d<10 && !found;++d) for (int dy=-d;dy<=d && !found;++dy) + for (int dx=-d;dx<=d && !found;++dx) { + if (abs(dx)!=d && abs(dy)!=d) continue; + int x=ob->tilex+dx,y=ob->tiley+dy;if (x<1 || y<1 || x>62 || y>62) continue; + player.x=x*TILEGLOBAL+32768;player.y=y*TILEGLOBAL+32768; + player.tilex=x;player.tiley=y;ConnectAreas(); + if (TryMove(&player) && CheckLine(ob)) { found=true;Aim(ob); } + } + CHECK(found);CHECK(ThreeDRefresh() && DrawStatus()); +} +static void Capture(const char *name) +{ + const char *dir=getenv("WOLF3D_CAPTURE_DIR");if (!dir) return; + char path[1024];int n=snprintf(path,sizeof(path),"%s/e%u-%s.bmp",dir,ep+1,name); + CHECK(n>0 && (size_t)n=0) { + for (unsigned d=0;d<4 && !collected;++d) { + player.x=statobjlist[i].tilex*TILEGLOBAL+32768-dx[d]*0xa000; + player.y=statobjlist[i].tiley*TILEGLOBAL+32768-dy[d]*0xa000; + player.tilex=player.x/TILEGLOBAL;player.tiley=player.y/TILEGLOBAL;player.angle=(int)d*90; + if (!TryMove(&player)) continue; + CHECK(ThreeDRefresh());collected=(gamestate.keys&1)!=0; + } + } + CHECK(collected); + bool exited=false; + for (unsigned i=0;i<4096 && !exited;++i) if (CA_Map()->planes[1][i]==99) { + player.tilex=(int)(i%64);player.tiley=(int)(i/64); + player.x=player.tilex*TILEGLOBAL+32768;player.y=player.tiley*TILEGLOBAL+32768; + player.angle=90;if (!TryMove(&player)) continue; + Thrust(90,0);exited=gamestate.victoryflag; + } + CHECK(exited); +} +static void Episode(bool owned) +{ + CHECK(DemoLoopStartGame(ticks));Steps(11); + CHECK(GameStartSelected(ticks,ep,2));ShutdownGameLevel();gamestate.mapon=8;CHECK(SetupGameLevel());CHECK(StartPreloadGraphics(ticks));TestFinishLoading(ticks);SD_StartMusic(SD_LevelMusic(ep,8)); + const int bosses[]={bossobj,schabbobj,mechahitlerobj,giftobj,gretelobj,fatobj}; + objtype *boss=Find(bosses[ep]);CHECK(boss);Arrange(boss);Capture("boss-start"); + GiveWeapon(wp_chaingun);gamestate.ammo=99;int initial=boss->hitpoints;Key(SDL_SCANCODE_LCTRL,true); + unsigned elapsed=0;bool transformed=false; + while (elapsed++<12000) { + if (!(boss->flags&FL_SHOOTABLE)) { + if (ep!=2 || transformed) break; + objtype *hitler=Find(realhitlerobj); + if (hitler) { boss=hitler;transformed=true;Arrange(boss);Capture("hitler-morph"); } + } + gamestate.health=100;gamestate.ammo=99; + if (boss->flags&FL_SHOOTABLE) { + if (!CheckLine(boss) || (elapsed%70)==0) Arrange(boss); + Aim(boss);CHECK(ThreeDRefresh()); + } + Step();CHECK(!gamestate.died); + } + Key(SDL_SCANCODE_LCTRL,false);Step(); + CHECK(elapsed<12000 && boss->hitpoints<=0 && initial>0); + CHECK(ep!=2 || transformed);Capture("boss-dead"); + if (ep==0 || ep==4) CollectKeyAndExit(); + unsigned waits=0;bool camera=false,replay=false; + while (!GameVictoryPresentation() && waits++<2500) { + gamestate.health=100;Step(); + if (DeathCameraActive() && !camera) { Capture("death-camera");camera=true; } + if (gamestate.victoryflag && !DeathCameraActive() && !replay) { Capture("victory-replay");replay=true; } + } + CHECK(GameVictoryPresentation() && DemoLoopState()==UI_GAME);Capture("statistics"); + unsigned map=(unsigned)(ep*10+8);CHECK(CA_Map()->number==map); + Tap(SDL_SCANCODE_RETURN);Capture("ending-page1"); + Tap(SDL_SCANCODE_RIGHT);Capture("ending-page2"); + Tap(SDL_SCANCODE_LEFT);Tap(SDL_SCANCODE_ESCAPE);Steps(61); + CHECK(DemoLoopState()==UI_RESULTS && !CA_Map() && !player.next); + Tap(SDL_SCANCODE_ESCAPE);Steps(61); + if(DemoLoopState()==UI_RESULTS) { Tap(SDL_SCANCODE_SPACE);Steps(61); } + CHECK(DemoLoopState()==UI_TITLE); + printf("E%u controlled %s weapon fight, finale, two article pages and menu return passed.\n",ep+1,owned ? "owned" : "synthetic"); +} +int main(int argc,char **argv) +{ + CHECK(argc==2 || argc==3);MM_Startup();CHECK(CA_Startup(argv[1]));CHECK(VL_Startup()); + SD_SetDigitizedMode(true);CHECK(Audio_Startup()); + CHECK(DemoLoopStartup(0,true));Steps(11); + if (argc==3) for (ep=0;ep<6;++ep) Episode(true); + else { ep=1;Episode(false); } + sd_status audio;SD_GetStatus(&audio);CHECK(audio.frames>0 && audio.writes>0); + GameStop();Audio_Shutdown();VL_Shutdown();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes());return 0; +} diff --git a/tests/finale_tests.c b/tests/finale_tests.c new file mode 100644 index 00000000..d9f36c9e --- /dev/null +++ b/tests/finale_tests.c @@ -0,0 +1,294 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_DEF.h" +#include "engine/ID_CA.h" +#include "engine/ID_SD.h" +#include "engine/ID_IN.h" +#include "engine/ID_US_1.h" +#include "engine/ID_VL.h" +#include "engine/ID_PM.h" +#include +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%d: %s (%s)\n",__LINE__,#x,CA_Error());exit(1); } } while (0) +static uint64_t ticks; +static soundnames events[1024];static unsigned eventcount; +static void Sound(soundnames sound,const objtype *ob) +{ + (void)ob;CHECK(eventcount<1024);events[eventcount++]=sound; +} +static unsigned Live(void) +{ + unsigned count=0;for (objtype *ob=player.next;ob;ob=ob->next) { CHECK(++count<=MAXACTORS);CHECK(ob->state); } + return count; +} +static void Place(int x,int y) +{ + player.tilex=x;player.tiley=y;player.x=x*TILEGLOBAL+32768; + player.y=y*TILEGLOBAL+32768;player.angle=90;ConnectAreas(); +} +static void Start(unsigned ep,unsigned diff) +{ + ticks=0;CHECK(GameStartSelected(0,ep,diff)); + ShutdownGameLevel();gamestate.mapon=8;CHECK(SetupGameLevel());eventcount=0; + CHECK(objcount==5 && Live()==5 && gamestate.killtotal==5); +} +static void Tick(void) { CHECK(GameStep(++ticks)); } +static void Tap(unsigned key) { IN_KeyEvent(key,true);IN_KeyEvent(key,false);Tick(); } +static void TestSpawns(void) +{ + const int hp[4][5]={{850,200,800,850,850},{950,300,950,950,950}, + {1550,400,1050,1050,1050},{2400,500,1200,1200,1200}}; + const int classes[]={schabbobj,fakeobj,mechahitlerobj,giftobj,fatobj}; + statetype *const states[]={&s_schabbstand,&s_fakestand,&s_mechastand,&s_giftstand,&s_fatstand}; + const int dirs[]={south,north,south,north,south}; + for (unsigned diff=0;diff<4;++diff) { + Start(0,diff); + for (unsigned i=0;i<5;++i) { + objtype *ob=&objlist[i];CHECK(ob->obclass==classes[i] && ob->state==states[i]); + CHECK(ob->hitpoints==hp[diff][i] && ob->dir==dirs[i] && ob->speed==512); + CHECK(ob->flags==(FL_SHOOTABLE|FL_AMBUSH)); + FirstSighting(ob);CHECK(ob->speed==1536 && (ob->flags&FL_ATTACKMODE)); + } + CHECK(s_schabbdie2.tictime==5 && s_hitlerdie2.tictime==5); + GameStop(); + } +} +static void TestAudioBossMode(void) +{ + for(unsigned mode=0;mode<2;++mode) { + SD_SetDigitizedMode(mode!=0);SD_SetEnabled(false,false); + Start(0,2); /* No SDL device is open, including in digitized mode. */ + int delay=mode?140:5; + CHECK(s_schabbdie2.tictime==delay && s_giftdie2.tictime==delay && + s_fatdie2.tictime==delay && s_hitlerdie2.tictime==delay); + SD_SetEnabled(true,true);CHECK(s_schabbdie2.tictime==delay); + SD_Shutdown();CHECK(s_schabbdie2.tictime==delay); + GameStop(); + } + SD_SetDigitizedMode(false); /* Restore legacy test fixture's logical mode. */ +} +static objtype *Projectile(int kind,statetype *state) +{ + objtype *ob=GetNewActor();CHECK(ob);ob->state=state;ob->ticcount=state->tictime; + ob->obclass=kind;ob->flags=FL_NEVERMARK;ob->active=true; + ob->x=20*TILEGLOBAL+32768;ob->y=20*TILEGLOBAL+32768; + ob->tilex=ob->tiley=20;ob->dir=nodir;ob->angle=0;return ob; +} +static void TestProjectileRules(void) +{ + Start(0,2);objtype *boss=&objlist[0];Place(14,30); + US_InitRndT(0);T_SchabbThrow(boss);objtype *p=boss; + for (objtype *ob=player.next;ob;ob=ob->next) p=ob; + CHECK(p->obclass==needleobj && p->speed==0x2000 && p->ticcount==1); + CHECK(p->x==boss->x && p->y==boss->y && p->angle==0 && p->flags==FL_NONMARK); + CHECK(events[0]==SCHABBSTHROWSND && US_RndT()==8); + int32_t x=p->x;DoActor(p);CHECK(p->x==x+FixedByFrac(8192,sintable[90]));RemoveActor(p); + /* Player-hit damage, original strict square, and wall-before-player order. */ + const int classes[]={needleobj,rocketobj,fireobj}; + statetype *states[]={&s_needle1,&s_rocket,&s_fire1}; + const int damage[]={21,31,1}; + for (unsigned i=0;i<3;++i) { + p=Projectile(classes[i],states[i]);Place(20,20);gamestate.health=100;US_InitRndT(0); + T_Projectile(p);CHECK(!p->state && gamestate.health==100-damage[i]); + RemoveActor(p);CHECK(Live()==5); + p=Projectile(classes[i],states[i]);player.x=p->x+0xc000;US_InitRndT(0); + T_Projectile(p);CHECK(p->state && US_RndT()==8);RemoveActor(p); + p=Projectile(classes[i],states[i]);p->x=21*TILEGLOBAL-1;p->speed=8192; + tilemap[21][20]=1;Place(21,20);gamestate.health=100;US_InitRndT(0); + T_Projectile(p);CHECK(gamestate.health==100 && US_RndT()==8); + if (classes[i]==rocketobj) { + CHECK(p->state==&s_boom1 && events[eventcount-1]==MISSILEHITSND); + for (unsigned tic=0;tic<15;++tic) DoActor(p); + CHECK(!p->state && Live()==5); + } else { CHECK(!p->state);RemoveActor(p); } + tilemap[21][20]=0; + } + /* Flames move on state actions, not on each simulation tic. */ + Place(2,2);T_FakeFire(&objlist[1]); + for (objtype *ob=player.next;ob;ob=ob->next) p=ob; + CHECK(p->speed==0x1200 && p->flags==FL_NEVERMARK && events[eventcount-1]==FLAMETHROWERSND); + p->angle=0;p->x=20*TILEGLOBAL+32768;p->y=20*TILEGLOBAL+32768;p->tilex=p->tiley=20; + x=p->x;for (unsigned tic=0;tic<13;++tic) DoActor(p); + CHECK(p->x==x+3*FixedByFrac(0x1200,sintable[90]));RemoveActor(p); + /* Closed doors and static blocks stop projectiles; live actors do not. */ + p=Projectile(needleobj,&s_needle1);tilemap[20][20]=128;CHECK(!ProjectileTryMove(p)); + doorobjlist[0].action=dr_open;CHECK(ProjectileTryMove(p));tilemap[20][20]=0; + staticblock[20][20]=true;CHECK(!ProjectileTryMove(p));staticblock[20][20]=false; + actorat[20][20]=boss;CHECK(ProjectileTryMove(p));actorat[20][20]=NULL; + p->x=1;p->angle=180;p->speed=8192;T_Projectile(p);CHECK(!p->state);RemoveActor(p); + GameStop(); +} +static void TestBurstsAndMorph(void) +{ + Start(2,2);Place(18,27);objtype *fake=&objlist[1];NewState(fake,&s_fakeshoot1); + unsigned before=Live(); + for (unsigned tic=0;tic<64;++tic) DoActor(fake); + CHECK(Live()==before+8 && fake->state==&s_fakeshoot9); + CHECK(eventcount==8);for (unsigned i=0;i<8;++i) CHECK(events[i]==FLAMETHROWERSND); + Start(5,2);Place(42,32);objtype *fat=&objlist[4];NewState(fat,&s_fatshoot1); + for (unsigned tic=0;tic<79;++tic) { gamestate.health=100;DoActor(fat); } + CHECK(eventcount==4 && events[0]==MISSILEFIRESND && Live()==6); + gamestate.health=100;DoActor(fat);CHECK(eventcount>=5 && events[4]==MISSILEFIRESND); + static const int realhp[]={500,700,800,900}; + for (unsigned diff=0;diff<4;++diff) { + Start(2,diff);objtype *mecha=&objlist[2]; + mecha->x+=123;mecha->y+=456;mecha->distance=12345;mecha->dir=northeast; + DamageActor(mecha,10000);CHECK(mecha->state==&s_mechadie1 && gamestate.score==5000); + unsigned flags=mecha->flags;US_InitRndT(0); + for (unsigned tic=0;tic<30;++tic) DoActor(mecha); + CHECK(mecha->state==&s_mechadie4 && Live()==6 && gamestate.killtotal==5); + objtype *hitler=mecha;for (objtype *ob=player.next;ob;ob=ob->next) hitler=ob; + CHECK(hitler!=mecha && hitler->obclass==realhitlerobj && hitler->state==&s_hitlerchase1); + CHECK(hitler->x==mecha->x && hitler->y==mecha->y && hitler->distance==12345); + CHECK(hitler->dir==northeast && hitler->flags==(flags|FL_SHOOTABLE)); + CHECK(hitler->speed==2560 && hitler->hitpoints==realhp[diff] && hitler->ticcount==2); + CHECK(US_RndT()==109);DamageActor(hitler,10000); + CHECK(gamestate.score==10000 && gamestate.killcount==2 && hitler->state==&s_hitlerdie1); + } + GameStop(); +} +static void TestPoolAndKiller(void) +{ + Start(0,2);objtype *slot=NULL; + for (unsigned i=0;i<1000;++i) { + A_Smoke(&objlist[0]);objtype *smoke=player.next;while (smoke->next) smoke=smoke->next; + if (slot) CHECK(slot==smoke); + slot=smoke; + for (unsigned tic=0;tic<15;++tic) DoActor(smoke); + CHECK(Live()==5 && !smoke->state); + } + objtype *p=Projectile(needleobj,&s_needle1);Place(20,20);gamestate.health=1;US_InitRndT(0); + T_Projectile(p);CHECK(gamestate.died && killerobj && killerobj->x==p->x); + int32_t x=killerobj->x;RemoveActor(p);objtype *reused=GetNewActor();CHECK(reused==p); + reused->state=&s_smoke1;reused->x=1;CHECK(killerobj->x==x);RemoveActor(reused); + while (Live()state=&s_smoke1;ob->flags=FL_NEVERMARK; + } + unsigned count=Live(),sounds=eventcount;US_InitRndT(0);T_GiftThrow(&objlist[3]); + CHECK(ActorAllocationFailed() && Live()==count && eventcount==sounds && US_RndT()==8); + CHECK(strstr(CA_Error(),"pool exhausted")!=NULL); + GameStop();CHECK(!player.next && !objcount && !ActorAllocationFailed()); +} +static void TestCamera(unsigned index,unsigned episode) +{ + Start(episode,2);objtype *boss=&objlist[index];Place(boss->tilex,boss->tiley+2); + if (boss->obclass==mechahitlerobj) { + DamageActor(boss,10000);for (unsigned i=0;i<30;++i) DoActor(boss); + for (objtype *ob=player.next;ob;ob=ob->next) if (ob->obclass==realhitlerobj) boss=ob; + } + int32_t killx=player.x,killy=player.y;StartDamageFlash(1000);DamageActor(boss,10000); + bool sawcamera=false,sawreplay=false; + while (!GameVictoryPresentation() && ticks<2000) { + gamestate.health=100;Tick(); + if (DeathCameraActive()) { + sawcamera=true; + if (player.state!=&s_deathcam) CHECK(!memcmp(palette,gamepal,768)); + } + if (gamestate.victoryflag && !DeathCameraActive()) sawreplay=true; + } + CHECK(sawcamera && sawreplay && GameVictoryPresentation() && playstate==ex_victorious); + CHECK(gamestate.killx==killx && gamestate.killy==killy); + CHECK(player.x!=killx || player.y!=killy);CHECK(!GameFinished()); + CHECK(player.state==&s_deathcam); + unsigned map=CA_Map()->number;Tap(sc_Enter);CHECK(!GameFinished()); + Tap(sc_RightArrow);Tap(sc_LeftArrow);Tap(sc_Escape);CHECK(GameFinished() && CA_Map()->number==map); + GameStop(); +} +static void TestBJ(unsigned episode) +{ + Start(episode,2);Place(50,21);Thrust(90,TILEGLOBAL); + CHECK(gamestate.victoryflag && Live()==6); + objtype *bj=player.next;while (bj->next) bj=bj->next; + CHECK(bj->obclass==bjobj && bj->temp1==6 && bj->dir==north); + bool jump=false; + while (!GameVictoryPresentation() && ticks<1500) { + Tick();if (bj->state->shapenum==SPR_BJ_JUMP4) jump=true; + } + CHECK(jump && playstate==ex_victorious && GameVictoryPresentation() && player.angle==270); + unsigned yells=0;for (unsigned i=0;inext;RemoveActor(ob);ob=next; } + statetype first={false,SPR_BOSS_W1,0,NULL,NULL,NULL}; + statetype second={false,SPR_GRETEL_W1,0,NULL,NULL,NULL}; + objtype *old=GetNewActor();CHECK(old);old->state=&first; + objtype *earlier=GetNewActor();CHECK(earlier);earlier->state=&second; + RemoveActor(old);objtype *later=GetNewActor();CHECK(later==old);later->state=&first; + CHECK(player.next==earlier && earlier->next==later && !later->next); + earlier->x=later->x=4*TILEGLOBAL+32768;earlier->y=later->y=2*TILEGLOBAL+32768; + earlier->tilex=later->tilex=4;earlier->tiley=later->tiley=2; + w3r_byte *a=(w3r_byte *)PM_GetPage(PMSpriteStart+SPR_BOSS_W1,NULL); + w3r_byte *b=(w3r_byte *)PM_GetPage(PMSpriteStart+SPR_GRETEL_W1,NULL); + memset(a+14,10,32);memset(b+14,20,32);Place(2,2);player.angle=0;gamestate.victoryflag=true; + CHECK(ThreeDRefresh());CHECK(framebuffer[(VIEWY+61)*320+VIEWX+119]==10); + GameStop(); +} +static void TestCameraTiming(void) +{ + Start(1,2);gamestate.killx=player.x;gamestate.killy=player.y; + A_StartDeathCam(&objlist[0]);unsigned count=0; + while (DeathCameraActive() && count<1000) { CHECK(StepDeathCamera());++count; } + /* 100 wait + ceil(131071/(64000/70)) grey fizzle + 300 acknowledgement + + ceil(131071/(64000/20)) viewport replay fizzle. */ + CHECK(count==585 && player.state==&s_deathcam && player.temp1==0); + A_StartDeathCam(&objlist[0]); + for (unsigned i=0;i<99;++i) { CHECK(StepDeathCamera());CHECK(playstate==ex_playing); } + CHECK(StepDeathCamera() && playstate==ex_victorious);GameStop(); +} +static void TestVictoryStats(void) +{ + Start(0,2);gamestate.score=1234; + for (unsigned i=0;i<8;++i) LevelRatios[i]=(levelratio_t){80+i,20+i,50+i,61+i,0,0}; + CHECK(DrawVictory() && gamestate.score==1234); + CHECK(framebuffer[112*320+208]==L_NUM0PIC+8 && framebuffer[112*320+224]==L_NUM0PIC+3); + CHECK(framebuffer[128*320+208]==L_NUM0PIC+2 && framebuffer[128*320+224]==L_NUM0PIC+3); + CHECK(framebuffer[144*320+208]==L_NUM0PIC+5 && framebuffer[144*320+224]==L_NUM0PIC+3); + CHECK(framebuffer[64*320+112]==L_NUM0PIC && framebuffer[64*320+128]==L_NUM0PIC+8); + CHECK(framebuffer[64*320+152]==L_NUM0PIC+3 && framebuffer[64*320+168]==L_NUM0PIC+6); + for (unsigned i=0;i<8;++i) LevelRatios[i].seconds=5940; + CHECK(DrawVictory() && framebuffer[64*320+112]==L_NUM0PIC+9 && framebuffer[64*320+168]==L_NUM0PIC+9); + gamestate.difficulty=0;CHECK(DrawVictory() && framebuffer[64*320+240]==127); + GameStop(); +} +static void TestCinematicControls(void) +{ + Start(1,2); + for (objtype *ob=player.next;ob;) { objtype *next=ob->next;RemoveActor(ob);ob=next; } + gamestate.victoryflag=true;player.state=&s_deathcam; + int32_t x=player.x,y=player.y;int angle=player.angle,ammo=gamestate.ammo; + IN_KeyEvent(sc_UpArrow,true);IN_KeyEvent(sc_RightArrow,true); + IN_KeyEvent(sc_Space,true);IN_KeyEvent(0x1d,true);US_InitRndT(0); + for (unsigned i=0;i<200;++i) Tick(); + CHECK(player.x==x && player.y==y && player.angle==angle && gamestate.ammo==ammo); + CHECK(US_RndT()==8); /* A death camera has no face-look RNG thinker. */ + GameStop(); +} +static void TestRestartAndArticles(void) +{ + Start(1,2);gamestate.oldscore=1234;TakeDamage(100,NULL); + while (gamestate.died && ticks<600) Tick(); + CHECK(!gamestate.died && gamestate.mapon==8 && gamestate.score==1234 && objlist[0].hitpoints==1550); + for (unsigned ep=0;ep<6;++ep) { + gamestate.episode=(int)ep;CHECK(StartEndText()); + bool done=false;IN_KeyEvent(sc_RightArrow,true);IN_KeyEvent(sc_RightArrow,false); + CHECK(StepEndText(&done) && !done);ResetEndText(); + } + w3r_byte *article=grsegs[T_ENDART1];size_t size=grsizes[T_ENDART1]; + w3r_byte saved=article[1];article[1]='X';gamestate.episode=0; + CHECK(!StartEndText());article[1]=saved;CHECK(StartEndText()); + size_t at=0;while (at+1 +int main(void) +{ + wl_frame_clock c={0}; + assert(WL_FrameClockAlpha(&c,100)==0.0); + WL_FrameClockObserve(&c,100); + assert(WL_FrameClockAlpha(&c,110)==0.0); + WL_FrameClockObserve(&c,200); + assert(WL_FrameClockAlpha(&c,200)==0.0); + assert(WL_FrameClockAlpha(&c,250)==0.5); + assert(WL_FrameClockAlpha(&c,400)==1.0); + WL_FrameClockObserve(&c,200);assert(WL_FrameClockAlpha(&c,250)==0.5); + WL_FrameClockObserve(&c,150); /* Clock regression resets presentation. */ + assert(WL_FrameClockAlpha(&c,180)==0.0); + WL_FrameClockReset(&c); + assert(WL_FrameClockAlpha(&c,1000)==0.0); + const unsigned rates[]={60,75,90,120,144,165,180,240,1000}; + for(unsigned n=0;n +#include +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%d: %s (%s; %s)\n",__LINE__,#x,CA_Error(),VL_Error()); exit(1); } } while (0) +static void Key(SDL_Scancode scan, bool down) +{ + SDL_Event event; memset(&event,0,sizeof(event)); + event.type = down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; + event.key.scancode = scan; CHECK(SDL_PushEvent(&event)); +} +static void Tap(SDL_Scancode scan) { Key(scan,true); Key(scan,false); } +static void Step(uint64_t ticks) { CHECK(!VL_PollQuit()); CHECK(DemoLoop(ticks)); CHECK(VW_UpdateScreen()); } +int main(int argc,char **argv) +{ + CHECK(argc == 2); MM_Startup(); CHECK(CA_Startup(argv[1])); CHECK(VL_Startup()); + CHECK(DemoLoopStartup(0,false)); + Tap(SDL_SCANCODE_RETURN); Step(0); Step(40); CHECK(DemoLoopState() == UI_MENU); + Key(SDL_SCANCODE_DOWN,true); Step(41); CHECK(MainItems.curpos == backtodemo); + Step(60); CHECK(MainItems.curpos == backtodemo); + Step(61); CHECK(MainItems.curpos == quit); + Key(SDL_SCANCODE_DOWN,false); Step(62); + Tap(SDL_SCANCODE_RETURN); Step(63); CHECK(DemoLoopState() == UI_CONFIRM); + Tap(SDL_SCANCODE_N); Step(64); CHECK(DemoLoopState() == UI_MENU); + Tap(SDL_SCANCODE_V); Step(65); CHECK(MainItems.curpos == viewscores); + Tap(SDL_SCANCODE_RETURN); Step(66); Step(86); CHECK(DemoLoopState() == UI_SCORES); + Tap(SDL_SCANCODE_ESCAPE); Step(87); Step(107); CHECK(DemoLoopState() == UI_MENU); + Tap(SDL_SCANCODE_Q); Tap(SDL_SCANCODE_RETURN); Step(108); CHECK(DemoLoopState() == UI_CONFIRM); + Tap(SDL_SCANCODE_Y); Step(109); Step(119); CHECK(DemoLoopState() == UI_DONE); + VL_Shutdown(); CA_Shutdown(); MM_Shutdown(); CHECK(MM_TotalBytes() == 0); + puts("SDL events drive original menu, scores, held navigation and clean quit."); + return 0; +} diff --git a/tests/game_fixtures.py b/tests/game_fixtures.py new file mode 100644 index 00000000..20d2b4a5 --- /dev/null +++ b/tests/game_fixtures.py @@ -0,0 +1,178 @@ +"""Synthetic map/page archives. No original game data is embedded.""" +import struct +from test_engine import fixtures +TAG=0xabcd + +def map_files(directory, transform=None): + walls=[107]*4096 + for y in range(64): + for x in range(64): + if x in (0,63) or y in (0,63): walls[y*64+x]=1 + for y in range(1,6): walls[y*64+6]=1 + walls[2*64+6]=90 + objects=[0]*4096;objects[2*64+2]=20 + planes=[walls,objects,[7]*4096] + if transform: transform(planes) + graph=bytearray(8+38) + header=bytearray(38) + for plane,words in enumerate(planes): + rlew=[8192];i=0 + while i3 or words[i]==TAG: rlew.extend((TAG,n,words[i])) + else: rlew.extend([words[i]]*n) + i+=n + carmack=bytearray(struct.pack('>8 in (0xa7,0xa8): carmack.extend(bytes((0,value>>8,value&255))) + else: carmack.extend(struct.pack('>8;count=word&255 + if high not in (0xa7,0xa8):words.append(word);continue + if not count:words.append(high*256+chunk[cursor]);cursor+=1;continue + if high==0xa7:source=len(words)-chunk[cursor];cursor+=1 + else:source=struct.unpack_from(' +#include +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%d: %s (%s; %s)\n",__LINE__,#x,CA_Error(),VL_Error()); exit(1); } } while(0) +#include "finish_loading.h" +static void Key(SDL_Scancode scan,bool down) +{ + SDL_Event event;memset(&event,0,sizeof(event));event.type=down ? SDL_EVENT_KEY_DOWN : SDL_EVENT_KEY_UP; + event.key.scancode=scan;CHECK(SDL_PushEvent(&event)); +} +static void Tap(SDL_Scancode scan) { Key(scan,true);Key(scan,false); } +static void Step(uint64_t ticks) { CHECK(!VL_PollQuit());CHECK(DemoLoop(ticks));if(GameLoading()) TestFinishLoading(ticks);CHECK(VW_UpdateScreen()); } +int main(int argc,char **argv) +{ + CHECK(argc==2);MM_Startup();CHECK(CA_Startup(argv[1]));CHECK(VL_Startup());CHECK(GameProbe()); + MainMenu[newgame].active=1;MainItems.curpos=viewscores;CHECK(DemoLoopStartup(0,true));Step(10); + Tap(SDL_SCANCODE_N);Tap(SDL_SCANCODE_RETURN);Step(11);Step(31);CHECK(DemoLoopState()==UI_EPISODE); + Tap(SDL_SCANCODE_RETURN);Step(32);Step(52);CHECK(DemoLoopState()==UI_DIFFICULTY); + Tap(SDL_SCANCODE_RETURN);Step(53);Step(73);CHECK(DemoLoopState()==UI_GAME); + int32_t x=player.x;Key(SDL_SCANCODE_UP,true);Step(74);CHECK(player.x>x);Step(82);x=player.x; + SDL_Event event;memset(&event,0,sizeof(event));event.type=SDL_EVENT_WINDOW_FOCUS_LOST;CHECK(SDL_PushEvent(&event)); + Step(83);CHECK(player.x==x); + event.type=SDL_EVENT_WINDOW_FOCUS_GAINED;CHECK(SDL_PushEvent(&event)); + Tap(SDL_SCANCODE_RIGHT);Step(84);int angle=player.angle;CHECK(angle==359);Step(85);CHECK(player.angle==angle); + Key(SDL_SCANCODE_LCTRL,true);Step(86);CHECK(gamestate.attackframe==1); + Key(SDL_SCANCODE_RCTRL,true);Step(92); + Key(SDL_SCANCODE_LCTRL,false);Step(98);CHECK(gamestate.ammo==7); + Step(104);Step(110);Step(112);CHECK(gamestate.ammo==7 && !gamestate.attackframe); + event.type=SDL_EVENT_WINDOW_FOCUS_LOST;CHECK(SDL_PushEvent(&event));Step(113); + event.type=SDL_EVENT_WINDOW_FOCUS_GAINED;CHECK(SDL_PushEvent(&event)); + Tap(SDL_SCANCODE_RCTRL);Step(114);Step(120);Step(126);CHECK(gamestate.ammo==6); + Tap(SDL_SCANCODE_ESCAPE);Tap(SDL_SCANCODE_RETURN);Step(127);Step(147);CHECK(DemoLoopState()==UI_MENU); + Step(148);CHECK(DemoLoopState()==UI_MENU); /* No Enter leakage into a second game. */ + GameStop();VL_Shutdown();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); + puts("SDL New Game, movement, Ctrl aliases, semi-auto fire, focus loss and menu transitions passed.");return 0; +} diff --git a/tests/game_tests.c b/tests/game_tests.c new file mode 100644 index 00000000..2702e7b7 --- /dev/null +++ b/tests/game_tests.c @@ -0,0 +1,520 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_DEF.h" +#include "engine/WL_SAVE.h" +#include "engine/ID_CA.h" +#include "engine/ID_PM.h" +#include "engine/ID_IN.h" +#include "engine/ID_VL.h" +#include "engine/WL_MENU.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_PRESENT.h" +#include +#include +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%d: %s (%s)\n",__LINE__,#x,CA_Error()); exit(1); } } while (0) +#include "finish_loading.h" +extern statetype s_grdstand; +static void TestExpand(void) +{ + uint16_t out[12]; memset(out,0xcc,sizeof(out)); + const unsigned char near[]={0x34,0x12,3,0xa7,1}; + CHECK(CAL_CarmackExpand(near,sizeof(near),out,4)); + for(unsigned i=0;i<4;++i) CHECK(out[i]==0x1234); + CHECK(out[4]==0xcccc); + const unsigned char far[]={1,0,2,0,4,0xa8,0,0}; + CHECK(CAL_CarmackExpand(far,sizeof(far),out,6)); + for(unsigned i=0;i<6;++i) CHECK(out[i]==(i%2 ? 2 : 1)); + const unsigned char escape[]={0,0xa7,0x34,0,0xa8,0x56}; + CHECK(CAL_CarmackExpand(escape,sizeof(escape),out,2)); CHECK(out[0]==0xa734 && out[1]==0xa856); + const unsigned char invalid[]={1,0xa7,0}; + CHECK(!CAL_CarmackExpand(invalid,sizeof(invalid),out,1)); + CHECK(!CAL_CarmackExpand(far,6,out,6)); + CHECK(!CAL_CarmackExpand(escape,2,out,1)); + CHECK(!CAL_CarmackExpand(near,sizeof(near),out,3)); + for(size_t n=0;n>24); } + (void)CAL_CarmackExpand(bytes,32,guarded+1,16); + CHECK(guarded[0]==0x5757 && guarded[17]==0x5757); + } +} +static void TestFixed(void) +{ + CHECK(FixedByFrac(65536,32768)==32768); + CHECK(FixedByFrac(-65536,32768)==-32768); + CHECK(FixedByFrac(-65536,0x80008000U)==32768); + CHECK(FixedByFrac(65536,0x00010000U)==0); /* Cardinal high word is NOT 16.16 unity. */ + CHECK(FixedByFrac(INT32_MIN,0x8000ffffU)==2147450880); + CHECK(FixedByFrac(INT32_MAX,0x0000ffffU)==2147450879); + CHECK(WL_FloorShift(-1,16)==-1 && WL_FloorShift(-65537,16)==-2); + CHECK(WL_FloorShift(INT64_MIN,63)==-1 && WL_FloorShift(INT64_MIN,16)==INT32_MIN); +} +static void Key(unsigned scan) { IN_KeyEvent(scan,true);IN_KeyEvent(scan,false); } +static void TestInputMenu(void) +{ + CHECK(SetupControlPanel(0)); MainItems.curpos=viewscores; + Key(0x30); Key(0x2f); /* B then V between polls: both consumed in order. */ + CHECK(HandleMenu(0)==-2 && MainItems.curpos==viewscores); + MainItems.curpos=quit; CHECK(HandleMenu(1)==-2 && MainItems.curpos==quit); /* No stale shortcut. */ + Key(0x30); Key(sc_Enter); CHECK(HandleMenu(2)==backtodemo); + CHECK(HandleMenu(3)==-2); /* Enter consumed once, not held by its queued text. */ + Key(sc_Escape); Key(sc_Enter); CHECK(HandleMenu(4)==-1); + CHECK(HandleMenu(5)==-2); /* All confirmation edges consumed atomically. */ + IN_ClearKeysDown(); +} +static void TestScale(void) +{ + unsigned char column[64]; for(unsigned i=0;i<64;++i) column[i]=(unsigned char)i; + memset(framebuffer,255,VL_PIXELS); ScalePost(0,1,256,column); /* 64-pixel wall. */ + for(unsigned y=0;y<64;++y) CHECK(framebuffer[(VIEWY+28+y)*320+VIEWX]==y); + CHECK(framebuffer[(VIEWY+27)*320+VIEWX]==255); + CHECK(framebuffer[(VIEWY+92)*320+VIEWX]==255); +} +static void TestWorld(bool synthetic,const char *dump) +{ + CHECK(SetupGameLevel()); + CHECK(CA_Map() && CA_Map()->number==0); + if(synthetic) { + CHECK(player.tilex==2 && player.tiley==2 && player.angle==0); + for(unsigned i=0;i<4096;++i) CHECK(CA_Map()->planes[2][i]==7); + } else CHECK(player.tilex==29 && player.tiley==57 && player.angle==0); + size_t size;const unsigned char *page=PM_GetPage(1,&size);CHECK(page && size==4096); + if(dump) { + FILE *out=fopen(dump,"wb");CHECK(out); + for(unsigned plane=0;plane<3;++plane) for(unsigned i=0;i<4096;++i) { + unsigned value=CA_Map()->planes[plane][i]; + unsigned char bytes[2]={(unsigned char)value,(unsigned char)(value>>8)}; + CHECK(fwrite(bytes,1,2,out)==2); + } + CHECK(fwrite(page,1,4096,out)==4096);CHECK(fclose(out)==0); + } + CHECK(PM_GetPage(1,NULL)==page); + if(synthetic) { + for(unsigned x=0;x<64;++x) for(unsigned y=0;y<64;++y) CHECK(page[x*64+y]==(x*3+y+17)%256); + unsigned char pixels[4096],mask[4096]; CHECK(PM_DecodeSprite(0,pixels,mask)); + CHECK(!mask[31*64+31] && mask[32*64+31] && pixels[32*64+31]==100); + CHECK(pixels[63*64+31]==131 && !mask[32*64+30]); + unsigned char *sprite=(unsigned char *)PM_GetPage(PMSpriteStart,NULL); + unsigned char saved[46];memcpy(saved,sprite,46); + sprite[0]=64;CHECK(!PM_DecodeSprite(0,pixels,mask));memcpy(sprite,saved,46); + sprite[4]=254;sprite[5]=255;CHECK(!PM_DecodeSprite(0,pixels,mask));memcpy(sprite,saved,46); + sprite[6]=129;CHECK(!PM_DecodeSprite(0,pixels,mask));memcpy(sprite,saved,46); + sprite[8]=0;sprite[9]=128;CHECK(!PM_DecodeSprite(0,pixels,mask));memcpy(sprite,saved,46); + rayhit hit; CHECK(AsmRefresh(0,&hit)); + CHECK(hit.side==2 && hit.x==6*65536+32768 && hit.column==31 && hit.page==1); + /* Replace the closed door with its original wall tile for an exact normal-hit oracle. */ + tilemap[6][2]=1; + CHECK(AsmRefresh(0,&hit)); + CHECK(hit.side==1 && hit.grid==6 && hit.x==6*65536 && hit.y==163622 && hit.column==31 && hit.page==1 && hit.height==171); + for(int angle=0;angle<360;angle+=15) { + player.angle=angle; CHECK(AsmRefresh(angle*10,&hit)); + CHECK(hit.column<64 && hit.page0); + } + player.angle=90;CHECK(AsmRefresh(900,&hit));CHECK(hit.side==0 && hit.y==65536 && hit.page==0); + player.angle=180;CHECK(AsmRefresh(1800,&hit));CHECK(hit.side==1 && hit.x==65536 && hit.page==1); + player.angle=270;CHECK(AsmRefresh(2700,&hit));CHECK(hit.side==0 && hit.y==63*65536 && hit.page==0); + player.angle=90;tilemap[2][1]=128; + doorobjlist[0].vertical=false;doorobjlist[0].lock=2; + CHECK(AsmRefresh(900,&hit));CHECK(hit.side==2 && hit.y==98304 && hit.page==6); + tilemap[2][1]=0; + player.angle=0; + int32_t x=player.x,y=player.y; ControlMovement(0,-35,false); + CHECK(player.x==x+5249 && player.y==y); + player.x=x;player.y=y;ControlMovement(35,0,true); CHECK(player.x==x && player.y==y+5249); + player.x=6*65536-MINDIST-100;player.y=y; ClipMove(&player,1000,1000); + CHECK(player.x==6*65536-MINDIST-100 && player.y==y+1000); + CHECK(!CA_CacheMap(60)); CHECK(CA_Map()); /* Rejected request preserves valid map. */ + } else { + unsigned char pixels[4096],mask[4096]; + /* Every non-sparse Steam sprite is validated in place, without importing art. */ + for(unsigned sprite=0;sprite InitObjects resets actorat/staticblock. */ +} +static void TestDoors(void) +{ + CHECK(SetupGameLevel()); + doorobj_t *d=&doorobjlist[0]; + player.x=(int32_t)(d->x*65536)-MINDIST-100; + player.y=(int32_t)(d->y*65536)+32768;player.tilex=(int)d->x-1;player.tiley=(int)d->y;player.angle=0; + d->lock=0;d->vertical=true; + Cmd_Use();CHECK(d->action==dr_opening && DoorSolid(0)); + for(unsigned i=0;i<63;++i) MoveDoors(); + CHECK(d->position==64512 && DoorSolid(0)); + actorat[d->x][d->y]=&objlist[0]; /* stale destination from a death */ + MoveDoors();CHECK(!actorat[d->x][d->y]); + CHECK(d->position==65535 && !DoorSolid(0)); + int32_t x=player.x;ClipMove(&player,1000,0);CHECK(player.x==x+1000); + player.tilex=(int)d->x;player.x=(int32_t)(d->x*65536)+32768; + for(unsigned i=0;i<301;++i) MoveDoors(); + CHECK(d->action==dr_open && d->ticcount==301); + d->ticcount=32767;MoveDoors();CHECK(d->ticcount==32768 && d->action==dr_open); + d->ticcount=65535;MoveDoors();CHECK(d->ticcount==0 && d->action==dr_open); + d->ticcount=301; + player.tilex=(int)d->x-2;player.x=(int32_t)(d->x*65536)-2*65536; + MoveDoors();CHECK(d->action==dr_closing && DoorSolid(0)); + for(unsigned i=0;i<64;++i) MoveDoors(); + CHECK(d->position==0 && d->action==dr_closed); + d->lock=1;OperateDoor(0);CHECK(d->action==dr_closed); + /* DOS checks the center row/column, not diagonal square corners. */ + int32_t left=(int32_t)d->x*65536,top=(int32_t)d->y*65536; + for(unsigned vertical=0;vertical<2;++vertical) for(unsigned corner=0;corner<4;++corner) { + d->vertical=vertical!=0;d->action=dr_open;d->position=65535; + player.x=(corner&1) ? left+65536+MINDIST-1 : left-MINDIST; + player.y=(corner&2) ? top+65536+MINDIST-1 : top-MINDIST; + player.tilex=player.x/65536;player.tiley=player.y/65536; + CloseDoor(0);CHECK(d->action==dr_closing); + d->position=60000;MoveDoors(); + CHECK(d->action==dr_closing && d->position==58976); + } + for(unsigned vertical=0;vertical<2;++vertical) { + d->vertical=vertical!=0;d->action=dr_open;d->position=65535; + player.x=vertical ? left-MINDIST : left+32768; + player.y=vertical ? top+32768 : top-MINDIST; + player.tilex=player.x/65536;player.tiley=player.y/65536; + CloseDoor(0);CHECK(d->action==dr_open); + player.x=left+32768;player.y=top+32768; + player.tilex=(int)d->x;player.tiley=(int)d->y; + d->action=dr_closing;MoveDoors();CHECK(d->action==dr_opening); + } + player.x=left-MINDIST-1;player.y=top-MINDIST-1; + player.tilex=player.x/65536;player.tiley=player.y/65536; + d->action=dr_open;CloseDoor(0);CHECK(d->action==dr_closing); + ShutdownGameLevel(); +} +static void TestSimulation(void) +{ + CHECK(GameStart(0));CHECK(framebuffer[(VIEWY+VIEWHEIGHT)*320+VIEWX-1]==124); IN_KeyEvent(sc_UpArrow,true); + for(uint64_t t=1;t<=9;++t) CHECK(GameStep(t)); + objtype fine=player; + CHECK(GameStart(0)); IN_KeyEvent(sc_UpArrow,true);CHECK(GameStep(9)); + CHECK(player.x==fine.x && player.y==fine.y && player.angle==fine.angle); + CHECK(GameStart(0)); IN_KeyEvent(sc_RightArrow,true); + for(uint64_t t=1;t<=9;++t) CHECK(GameStep(t)); + fine=player; + CHECK(GameStart(0));IN_KeyEvent(sc_RightArrow,true);CHECK(GameStep(9));CHECK(player.angle==fine.angle); + CHECK(GameStart(0)); int32_t initial=player.x; Key(sc_UpArrow); + CHECK(GameStep(0) && player.x==initial);CHECK(GameStep(1) && player.x>initial); + initial=player.x;CHECK(GameStep(2) && player.x==initial); + CHECK(GameStart(0));IN_KeyEvent(sc_UpArrow,true);IN_ClearKeysDown();initial=player.x; + CHECK(GameStep(1) && player.x==initial); + CHECK(GameStart(0));IN_KeyEvent(sc_LeftArrow,true);IN_KeyEvent(sc_RightArrow,true); + CHECK(GameStep(3) && player.angle==0); + CHECK(GameStart(0));IN_KeyEvent(sc_UpArrow,true);CHECK(GameStep(1000));fine=player; + CHECK(GameStart(0));IN_KeyEvent(sc_UpArrow,true);CHECK(GameStep(10));CHECK(player.x==fine.x && player.y==fine.y); + GameStop(); +} +typedef struct { + int32_t x,y; + int tilex,tiley,angle; + int health,ammo,lives,episode,mapon,difficulty; + uint32_t time_count; + int playstate; + unsigned objcount,statcount,doornum; + int door_action; + unsigned door_position,door_ticcount; + unsigned pwallstate,pwallpos; + int pwallx,pwally,pwalldir; + bool player_next_null,player_state_null; + bool actor_reserved,static_blocked,pushable_cell; + w3r_byte map_tile,door_tile; +} restart_state; +static void CaptureRestartState(restart_state *s) +{ + memset(s,0,sizeof(*s)); + s->x=player.x;s->y=player.y; + s->tilex=player.tilex;s->tiley=player.tiley;s->angle=player.angle; + s->health=gamestate.health;s->ammo=gamestate.ammo;s->lives=gamestate.lives; + s->episode=gamestate.episode;s->mapon=gamestate.mapon;s->difficulty=gamestate.difficulty; + s->time_count=gamestate.TimeCount;s->playstate=(int)playstate; + s->objcount=objcount;s->statcount=statcount;s->doornum=doornum; + CHECK(doornum==1); + s->door_action=(int)doorobjlist[0].action; + s->door_position=doorobjlist[0].position;s->door_ticcount=doorobjlist[0].ticcount; + s->pwallstate=pwallstate;s->pwallpos=pwallpos; + s->pwallx=pwallx;s->pwally=pwally;s->pwalldir=pwalldir; + s->player_next_null=player.next==NULL;s->player_state_null=player.state==NULL; + s->actor_reserved=actorat[10][10]!=NULL;s->static_blocked=staticblock[10][10]; + s->pushable_cell=pushable[10][10];s->map_tile=tilemap[10][10];s->door_tile=tilemap[6][2]; +} +static restart_state RunRestartCycle(void) +{ + restart_state before,after; + CHECK(GameStart(0)); + CaptureRestartState(&before); + CHECK(before.x==2*TILEGLOBAL+32768 && before.y==2*TILEGLOBAL+32768); + CHECK(before.tilex==2 && before.tiley==2 && before.angle==0); + CHECK(before.health==100 && before.ammo==8 && before.lives==3); + CHECK(before.playstate==ex_playing && before.time_count==0); + CHECK(before.objcount==0 && before.statcount==0 && before.doornum==1); + CHECK(before.door_action==dr_closed && before.door_position==0 && before.door_ticcount==0); + CHECK(before.door_tile==128 && before.map_tile==0); + CHECK(before.player_next_null && before.player_state_null); + CHECK(!before.actor_reserved && !before.static_blocked && !before.pushable_cell); + CHECK(before.pwallstate==0 && before.pwallpos==0); + CHECK(before.pwallx==0 && before.pwally==0 && before.pwalldir==0); + + Key(sc_UpArrow);CHECK(GameStep(1)); + CHECK(player.x!=before.x || player.y!=before.y); + + objtype *reserved=SpawnActor(10,10,&s_grdstand); + CHECK(reserved && actorat[10][10]==reserved); + staticblock[10][10]=true;tilemap[10][10]=1; + OpenDoor(0);MoveDoors(); + pushable[10][10]=true;pwallstate=1;pwallpos=32;pwallx=10;pwally=10;pwalldir=east; + CHECK(actorat[10][10] && staticblock[10][10] && tilemap[10][10]==1); + CHECK(doorobjlist[0].action==dr_opening && doorobjlist[0].position==1024); + CHECK(pwallstate==1 && pwallpos==32 && pushable[10][10]); + + GameStop(); + CHECK(!CA_Map() && !objcount && !statcount && !doornum); + CHECK(!actorat[10][10] && !staticblock[10][10] && !pushable[10][10]); + CHECK(pwallstate==0 && pwallpos==0); + CHECK(pwallx==0 && pwally==0 && pwalldir==0); + + CHECK(GameStart(0)); + CaptureRestartState(&after); + CHECK(memcmp(&before,&after,sizeof(before))==0); + return after; +} +static void TestRestart(void) +{ + restart_state first=RunRestartCycle(); + restart_state second=RunRestartCycle(); + CHECK(memcmp(&first,&second,sizeof(first))==0); + GameStop(); +} +/* Explicit scalar projection of authoritative state; no pointers or padding. */ +typedef struct { + int32_t x,y; + int tilex,tiley,angle; + uint32_t time_count; + int health,ammo,lives,keys,score; + int episode,mapon,difficulty,weapon; + int playstate; + unsigned objcount,statcount,doornum; + unsigned door_x,door_y,door_lock,door_position,door_ticcount; + int door_action; + bool door_vertical,door_reserved; + unsigned pwallstate,pwallpos; + w3r_byte door_tile; + bool player_next_null,player_state_null; +} replay_state; +static void CaptureReplayState(replay_state *s) +{ + const doorobj_t *d=&doorobjlist[0]; + memset(s,0,sizeof(*s)); + s->x=player.x;s->y=player.y; + s->tilex=player.tilex;s->tiley=player.tiley;s->angle=player.angle; + s->time_count=gamestate.TimeCount; + s->health=gamestate.health;s->ammo=gamestate.ammo;s->lives=gamestate.lives; + s->keys=gamestate.keys;s->score=gamestate.score; + s->episode=gamestate.episode;s->mapon=gamestate.mapon; + s->difficulty=gamestate.difficulty;s->weapon=gamestate.weapon; + s->playstate=(int)playstate; + s->objcount=objcount;s->statcount=statcount;s->doornum=doornum; + CHECK(doornum==1); + s->door_x=d->x;s->door_y=d->y;s->door_lock=d->lock; + s->door_vertical=d->vertical;s->door_action=(int)d->action; + s->door_position=d->position;s->door_ticcount=d->ticcount; + s->door_reserved=actorat[d->x][d->y]!=NULL; + s->door_tile=tilemap[d->x][d->y]; + s->pwallstate=pwallstate;s->pwallpos=pwallpos; + s->player_next_null=player.next==NULL;s->player_state_null=player.state==NULL; +} +/* Presentation is copied from authoritative state after a tic; it never + steps the simulation. Sample() writes only caller-owned storage. */ +static void StepPresent(uint64_t t,unsigned every,wl_present_snapshot *sample,unsigned *captures) +{ + CHECK(GameStep(t)); + if(every && t%every==0) { + WL_PresentCapture(t); + CHECK(WL_PresentSample(WL_TickNS(t),sample)); + CHECK(sample->simulation_clock==gamestate.TimeCount); + ++*captures; + } +} +/* Same logical input script for every session, one 70 Hz tic per GameStep. */ +static void ReplayInputs(unsigned every,wl_present_snapshot *sample,unsigned *captures) +{ + uint64_t t=0; + IN_KeyEvent(sc_UpArrow,true); /* walk east up to the closed door */ + for(unsigned i=0;i<40;++i) StepPresent(++t,every,sample,captures); + IN_KeyEvent(sc_UpArrow,false); + StepPresent(++t,every,sample,captures); + Key(sc_Space);StepPresent(++t,every,sample,captures); /* use the door */ + IN_KeyEvent(sc_UpArrow,true); + for(unsigned i=0;i<10;++i) StepPresent(++t,every,sample,captures); + IN_KeyEvent(sc_UpArrow,false); + IN_KeyEvent(sc_RightArrow,true); + for(unsigned i=0;i<4;++i) StepPresent(++t,every,sample,captures); + IN_KeyEvent(sc_RightArrow,false); + IN_KeyEvent(sc_UpArrow,true); + for(unsigned i=0;i<4;++i) StepPresent(++t,every,sample,captures); + IN_KeyEvent(sc_UpArrow,false); + StepPresent(++t,every,sample,captures); + CHECK(t==61); +} +static void CheckReplayStatesEqual(const replay_state *a,const replay_state *b) +{ + CHECK(a->x==b->x && a->y==b->y); + CHECK(a->tilex==b->tilex && a->tiley==b->tiley && a->angle==b->angle); + CHECK(a->time_count==b->time_count); + CHECK(a->health==b->health && a->ammo==b->ammo && a->lives==b->lives); + CHECK(a->keys==b->keys && a->score==b->score); + CHECK(a->episode==b->episode && a->mapon==b->mapon); + CHECK(a->difficulty==b->difficulty && a->weapon==b->weapon); + CHECK(a->playstate==b->playstate); + CHECK(a->objcount==b->objcount && a->statcount==b->statcount && a->doornum==b->doornum); + CHECK(a->door_x==b->door_x && a->door_y==b->door_y && a->door_lock==b->door_lock); + CHECK(a->door_vertical==b->door_vertical && a->door_action==b->door_action); + CHECK(a->door_position==b->door_position && a->door_ticcount==b->door_ticcount); + CHECK(a->door_reserved==b->door_reserved && a->door_tile==b->door_tile); + CHECK(a->pwallstate==b->pwallstate && a->pwallpos==b->pwallpos); + CHECK(a->player_next_null==b->player_next_null && a->player_state_null==b->player_state_null); +} +static replay_state RunReplaySession(void) +{ + replay_state s; + unsigned captures=0; + IN_ClearKeysDown(); /* no pressed/held keys leak into a fresh session */ + CHECK(GameStartMap(0,0,2,42)); /* fixed synthetic map, difficulty and seed */ + CHECK(player.tilex==2 && player.tiley==2 && player.angle==0); + CHECK(gamestate.TimeCount==0 && gamestate.health==100 && gamestate.ammo==8); + ReplayInputs(0,NULL,&captures); + CHECK(captures==0); + CaptureReplayState(&s); + CHECK(s.time_count==61 && s.playstate==ex_playing); + CHECK(s.x!=2*TILEGLOBAL+32768); /* movement really changed authoritative state */ + CHECK(s.door_action==dr_opening && s.door_position>0 && !s.door_reserved); + GameStop(); + return s; +} +static void TestDeterministicReplay(void) +{ + replay_state first=RunReplaySession(); + replay_state second=RunReplaySession(); + CheckReplayStatesEqual(&first,&second); +} +static replay_state RunPresentationSession(unsigned every,unsigned *captures) +{ + replay_state s; + wl_present_snapshot sample; + IN_ClearKeysDown(); + CHECK(GameStartMap(0,0,2,42)); + CHECK(player.tilex==2 && player.tiley==2 && player.angle==0); + *captures=0; + ReplayInputs(every,&sample,captures); + CaptureReplayState(&s); + GameStop(); + return s; +} +static void TestPresentationRateDeterminism(void) +{ + unsigned every_tick=0,every_fourth=0; + replay_state a=RunPresentationSession(1,&every_tick); + replay_state b=RunPresentationSession(4,&every_fourth); + CHECK(every_tick==61 && every_fourth==15); /* genuinely different schedules */ + CheckReplayStatesEqual(&a,&b); +} +/* Characterisation of Classic rendering side effects: ThreeDRefresh (not the + read-only WL_PresentSample path) marks spotvis, actor visibility and picks + up bonuses from DrawScaleds. Everything here is headless and deterministic. */ +static void TestClassicRenderSideEffects(void) +{ + CHECK(GameStart(0)); + /* Stand at the west edge of tile 3: its floor is ray-visible and the + bonus there is inside the original pickup projection distance. */ + player.x=3*TILEGLOBAL;player.y=2*TILEGLOBAL+32768; + player.tilex=3;player.tiley=2;player.angle=0; + memset(spotvis,0,sizeof(spotvis)); /* controlled pre-render baseline */ + objtype *visible=SpawnActor(4,2,&s_grdstand); + objtype *hidden=SpawnActor(10,10,&s_grdstand); + CHECK(visible && hidden); + visible->flags=0;hidden->flags=FL_VISABLE; /* render must flip both */ + PlaceItemType(bo_clip,3,2); + CHECK(statcount==1 && statobjlist[0].shapenum!=-1 && gamestate.ammo==8); + CHECK(!spotvis[3][2] && !spotvis[4][2] && !spotvis[10][10]); + CHECK(!(visible->flags&FL_VISABLE) && (hidden->flags&FL_VISABLE)); + + CHECK(ThreeDRefresh()); /* the exact Classic rendering function */ + + CHECK(spotvis[3][2] && spotvis[4][2]); /* rays mark traversed floor cells */ + CHECK(!spotvis[10][10]); /* cells behind the closed door stay invisible */ + CHECK(visible->flags&FL_VISABLE && visible->active); /* visible actor marked */ + CHECK(!(hidden->flags&FL_VISABLE)); /* hidden actor's stale flag cleared */ + CHECK(gamestate.ammo==16 && statobjlist[0].shapenum==-1); /* GetBonus via render */ + GameStop(); +} +static void TestOwnedWalk(void) +{ + CHECK(GameStart(0));int start=player.tilex,door=0; + for(int x=start+1;x<63;++x) if(tilemap[x][player.tiley]&128) { door=x;break; } + CHECK(door);bool used=false;IN_KeyEvent(sc_UpArrow,true); + for(uint64_t t=1;t<500 && player.tilex=door+2); + GameStop(); +} +static void TestMenuGame(void) +{ + CHECK(GameProbe()); MainMenu[newgame].active=1; MainItems.curpos=newgame; + CHECK(DemoLoopStartup(0,true) && DemoLoop(10)); Key(sc_Enter); + CHECK(DemoLoop(11) && DemoLoop(31) && DemoLoopState()==UI_EPISODE); + Key(sc_Enter);CHECK(DemoLoop(32) && DemoLoop(52) && DemoLoopState()==UI_DIFFICULTY); + Key(sc_Enter);CHECK(DemoLoop(53) && DemoLoop(73) && DemoLoopState()==UI_GAME); + TestFinishLoading(73);Key(sc_UpArrow); CHECK(DemoLoop(74)); + Key(sc_Escape); CHECK(DemoLoop(75) && DemoLoop(95) && DemoLoopState()==UI_MENU); + CHECK(CA_Map() && ChunksInFile && GameRunning()); + GameStop(); + MainMenu[newgame].active=0;MainItems.curpos=viewscores; +} +int main(int argc,char **argv) +{ + CHECK(argc>=2);TestExpand();TestFixed();TestScale();MM_Startup();CHECK(!GameProbe());CHECK(CA_Startup(argv[1])); + CHECK(VL_SetPalette(gamepal,768));TestInputMenu();TestWorld(argc==2,argc>3 ? argv[3] : NULL);TestMapBounds();if(argc==2) TestDoors();TestSimulation();if(argc==2) TestRestart();if(argc==2) TestDeterministicReplay();if(argc==2) TestPresentationRateDeterminism();if(argc==2) TestClassicRenderSideEffects();if(argc>2) TestOwnedWalk();TestMenuGame(); + GameStop();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); + puts("Original map/VSWAP, fixed-point ray/scaler, movement and menu/game tests passed.");return 0; +} diff --git a/tests/intermission_tests.c b/tests/intermission_tests.c new file mode 100644 index 00000000..1e9ddecf --- /dev/null +++ b/tests/intermission_tests.c @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_SAVE.h" +#include "engine/ID_CA.h" +#include "engine/ID_SD.h" +#include "engine/ID_US_1.h" +#include "engine/ID_VL.h" +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s)\n",__LINE__,#x,CA_Error());exit(1); } } while(0) +static soundnames events[256];static uint64_t times[256],now;static unsigned count; +static void Sound(soundnames sound,const objtype *actor) { (void)actor;CHECK(count<256);events[count]=sound;times[count++]=now; } +int main(int argc,char **argv) +{ + CHECK(argc==2);MM_Startup();CHECK(CA_Startup(argv[1]));CHECK(VL_SetPalette(gamepal,768));CHECK(GameStart(0)); + /* Invented AL sounds last one second (140 samples), even without SDL. */ + CHECK(SD_SoundTicks(ENDBONUS1SND)==70);SetGameSoundHook(Sound); + levelratio_t r={100,0,30,60,90,25000};unsigned rng=US_RndIndex();int score=gamestate.score; + CHECK(StartLevelIntermission(&r,0));CHECK(count==1 && events[0]==ENDBONUS1SND && LevelIntermissionCounting()); + uint8_t first[VL_PIXELS],second[VL_PIXELS];memcpy(first,framebuffer,sizeof(first)); + bool leave=false;now=10;CHECK(StepLevelIntermission(now,false,&leave));CHECK(!memcmp(first,framebuffer,sizeof(first))); + now=11;CHECK(StepLevelIntermission(now,false,&leave));CHECK(memcmp(first,framebuffer,sizeof(first))); + memcpy(second,framebuffer,sizeof(second));now=46;CHECK(StepLevelIntermission(now,false,&leave));CHECK(!memcmp(second,framebuffer,sizeof(second))); + now=47;CHECK(StepLevelIntermission(now,false,&leave));CHECK(!memcmp(first,framebuffer,sizeof(first))); + now=69;CHECK(StepLevelIntermission(now,false,&leave) && count==1 && gamestate.score==score); + now=70;CHECK(StepLevelIntermission(now,false,&leave) && count==2 && events[1]==ENDBONUS2SND); + for(now=71;now<5000 && LevelIntermissionCounting();++now) CHECK(StepLevelIntermission(now,false,&leave)); + CHECK(!LevelIntermissionCounting() && gamestate.score==score+25000 && US_RndIndex()==rng && !leave); + CHECK(count==21); /* time 2, kills 11+perfect, secrets 1+none, treasure 4+end */ + unsigned perfect=0,none=0; + for(unsigned i=0;i=times[i-1]); } + CHECK(perfect==1 && none==1 && events[count-1]==ENDBONUS2SND); + CHECK(StepLevelIntermission(now,true,&leave) && leave && gamestate.score==score+25000); + count=0;score=gamestate.score;now=6000;CHECK(StartLevelIntermission(&r,now)); + CHECK(StepLevelIntermission(now+1,true,&leave) && !leave && !LevelIntermissionCounting()); + CHECK(gamestate.score==score+25000 && US_RndIndex()==rng); + CHECK(StepLevelIntermission(now+2,true,&leave) && leave && gamestate.score==score+25000); + SetGameSoundHook(NULL);GameStop();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); + puts("Original intermission counts, sound waits, skip/confirm, single award and RNG passed.");return 0; +} diff --git a/tests/loading_tests.c b/tests/loading_tests.c new file mode 100644 index 00000000..83cc4f1a --- /dev/null +++ b/tests/loading_tests.c @@ -0,0 +1,193 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_DEF.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_MENU.h" +#include "engine/WL_SAVE.h" +#include "engine/WL_DISPLAY.h" +#include "engine/WL_PRESENT.h" +#include "engine/ID_CA.h" +#include "engine/ID_PM.h" +#include "engine/ID_IN.h" +#include "engine/ID_VH.h" +#include "engine/ID_US_1.h" +#include "engine/ID_SD.h" +#include "platform/sdl_video.h" +#include "platform/sdl_audio.h" +#include +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s; %s)\n",__LINE__,#x,CA_Error(),SDL_GetError());exit(1); } } while(0) +static uint64_t ticks; +static SDL_Window *window; +static SDL_Renderer *renderer; +static unsigned Uncached(void) +{ + unsigned n=0;for(unsigned p=0;p=-4 && rect.w*3-rect.h*4<=4); + CHECK(rect.x>=0 && rect.y>=0); + CHECK(rect.x*2+rect.w-(float)w>=-2 && rect.x*2+rect.w-(float)w<=2); + CHECK(rect.y*2+rect.h-(float)h>=-2 && rect.y*2+rect.h-(float)h<=2); +} +static void FinishLoading(void) +{ + unsigned n=0;while(GameLoading() && ++n<500) Pump();CHECK(!GameLoading()); +} +static void Bar(void) +{ + for(unsigned current=0;current<=5;++current) { + memset(framebuffer,201,VL_PIXELS);PreloadUpdate(current,5); + unsigned width=214*current/5; + for(unsigned y=0;y<200;++y) for(unsigned x=0;x<320;++x) { + unsigned expected=201; + if(y>=101 && y<=102 && x>=53 && x<267) { + unsigned column=x-53; + expected=columnx==attacker.x && killerobj->y==attacker.y); + attacker.x=attacker.y=0; /* Saved killer position survives actor reuse. */ + unsigned rng=US_RndIndex();uint32_t time=gamestate.TimeCount; + int angle=starts[a],target=targets[a],delta=(target-angle+540)%360-180; + unsigned tics=0; + do { + unsigned dt=a%2?3:1; + for(unsigned i=0;i2?2:delta< -2?-2:delta;angle=(angle+turn+360)%360;delta-=turn;++tics;if(!delta) { dt=i+1;break; } } + ticks+=dt;CHECK(GameStep(ticks));CHECK(player.angle==angle && gamestate.weapon==-1); + CHECK(WL_PresentCurrent() && WL_PresentCurrent()->died && WL_PresentCurrent()->weapon<=3); + if(a==1 && tics<=3) CHECK(VW_UpdateScreen()); + if(audio && tics<=3) { sd_status sound;SD_GetStatus(&sound);CHECK(sound.sound==PLAYERDEATHSND); } + } while(delta); + uint32_t seed;CHECK(GameDeathPresentation(&seed)==2 && seed==1 && player.angle==target); + if(a==1) CHECK(VW_UpdateScreen()); + w3r_byte before[VL_PIXELS];memcpy(before,framebuffer,sizeof(before)); + uint32_t expected_seed=1; + for(unsigned p=0;p<64000/70;++p) { + unsigned x=expected_seed>>8,y=(expected_seed-1)&255U; + expected_seed=(expected_seed>>1)^((expected_seed&1U)?UINT32_C(0x12000):0U); + if(x +#include +#include +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%s: %s / %s\n",#x,CA_Error(),SDL_GetError());exit(1); } } while(0) +wl_profile WL_Profile; +uint64_t WL_ProfileNow(void) { return SDL_GetTicksNS(); } +#ifdef WOLF3D_ALLOC_PROFILE +static atomic_ulong allocations; +void *__real_malloc(size_t n); +void *__real_calloc(size_t n,size_t s); +void *__real_realloc(void *p,size_t n); +void *__wrap_malloc(size_t n) { ++allocations;return __real_malloc(n); } +void *__wrap_calloc(size_t n,size_t s) { ++allocations;return __real_calloc(n,s); } +void *__wrap_realloc(void *p,size_t n) { ++allocations;return __real_realloc(p,n); } +#else +static atomic_ulong allocations; +#endif +static int Compare(const void *a,const void *b) +{ double x=*(const double *)a,y=*(const double *)b;return (x>y)-(x=1 && rate<=240); } + MM_Startup();CHECK(CA_Startup(argv[1])); + CHECK(VL_SetPalette(gamepal,768) && VL_Startup() && Audio_Startup()); + CHECK(DemoLoopStartup(VL_GetTicks70(),true)); + const unsigned sizes[][2]={{640,480},{1280,720},{1920,1080},{1920,1080}}; + int window_count;SDL_Window **windows=SDL_GetWindows(&window_count);CHECK(windows && window_count==1); + SDL_Renderer *renderer=SDL_GetRenderer(windows[0]);SDL_free(windows); + printf("video=%s, renderer=%s, audio=%s, smooth=%s; owned E1M1, view 19, 4 seconds/canvas\n", + SDL_GetCurrentVideoDriver(),SDL_GetRendererName(renderer),SDL_GetCurrentAudioDriver(),SDL_getenv("M9_NO_SMOOTH")?"off":"on"); + for(unsigned n=0;n<4;++n) { + CHECK(DemoLoopStartGame(VL_GetTicks70()) && NewViewSize(19)); + display_settings d;CHECK(VL_DisplayGet(&d));d.high_resolution=true;d.smooth=SDL_getenv("M9_NO_SMOOTH")==NULL; + d.render_width=sizes[n][0];d.render_height=sizes[n][1];d.aspect=2;d.scale=0;d.width=n==3?3840:1280;d.height=n==3?2160:720; + d.vsync=SDL_getenv("M8_VSYNC")!=NULL;CHECK(VL_DisplaySet(&d)); + /* Warm page caches, audio and texture allocation before measuring. */ + uint64_t warm_start=SDL_GetTicksNS(); + for(unsigned i=0;i<20 || SDL_GetTicksNS()-warm_start<300000000;++i) { CHECK(!VL_PollQuit());CHECK(DemoLoop(VL_GetTicks70()) && VW_UpdateScreen());Audio_Pump(); } + CHECK(VL_DisplayGet(&d)); + if(n==3 && (d.pixel_width!=3840 || d.pixel_height!=2160)) { + printf("4K output unavailable: drawable is %dx%d; no 4K measurement.\n",d.pixel_width,d.pixel_height); + continue; + } + uint64_t tick=VL_GetTicks70(),initial_tick=tick,start=SDL_GetTicksNS(),last=start,next=0; + GamePauseClock(tick);uint32_t initial_clock=gamestate.TimeCount; + double intervals[4096];unsigned count=0;clock_t cpu=clock();unsigned long initial_allocations=atomic_load(&allocations); + memset(&WL_Profile,0,sizeof(WL_Profile)); + while(SDL_GetTicksNS()-start<4000000000ULL && count<4096) { + CHECK(!VL_PollQuit());uint64_t now=SDL_GetTicksNS(); + for(unsigned steps=0;steps<8 && WL_TickNext(&tick,now);++steps) CHECK(DemoLoop(tick)); + Audio_Pump();now=SDL_GetTicksNS(); + double refresh=argc==3?strtod(argv[2],NULL):VL_MonitorRefreshRate(); + if(!d.smooth || now>=next) { + uint64_t begin=now;CHECK(VW_UpdateScreen());now=SDL_GetTicksNS(); + intervals[count++]=(double)(now-last)/1000000.0;last=now; + next=WL_PresentationDeadline(begin,now,refresh,VL_VSyncPaced(refresh)); + } + now=SDL_GetTicksNS();uint64_t wake=WL_TickNS(tick+1);if(nextnow) SDL_DelayNS(wake-now>4000000?4000000:wake-now); + } + uint64_t finish=SDL_GetTicksNS(); + double seconds=(double)(finish-start)/1000000000.0; + double cpu_percent=100.0*(double)(clock()-cpu)/CLOCKS_PER_SEC/seconds; + qsort(intervals,count,sizeof(*intervals),Compare); + double sum=0,squares=0;for(unsigned i=0;i0);CHECK(VL_Capture(path)); } + } + GameStop();Audio_Shutdown();VL_Shutdown();CA_Shutdown();MM_Shutdown();return 0; +} diff --git a/tests/presentation_tests.c b/tests/presentation_tests.c new file mode 100644 index 00000000..fc8939c4 --- /dev/null +++ b/tests/presentation_tests.c @@ -0,0 +1,165 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_PRESENT.h" +#include "engine/WL_RENDER.h" +#include "engine/WL_SAVE.h" +#include "engine/WL_CONTROLS.h" +#include "engine/ID_CA.h" +#include "engine/ID_VL.h" +#include "engine/ID_US_1.h" +#include +#include +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s)\n",__LINE__,#x,CA_Error());exit(1); } } while(0) +static statetype teststand={0,SPR_GRD_S_1,0,NULL,NULL,NULL}; +static uint32_t Hash(const void *p,size_t n) { const unsigned char *s=p;uint32_t h=2166136261U;while(n--) h=(h^*s++)*16777619U;return h; } +static uint32_t State(void) +{ + return Hash(&gamestate,sizeof(gamestate))^Hash(&player,sizeof(player))^Hash(objlist,sizeof(objlist))^ + Hash(tilemap,sizeof(tilemap))^Hash(spotvis,sizeof(spotvis))^Hash(doorobjlist,sizeof(doorobjlist))^ + Hash(framebuffer,VL_PIXELS)^US_RndIndex(); +} +static uint64_t Half(unsigned tick) { return WL_TickNS(tick)+(WL_TickNS(tick)-WL_TickNS(tick-1))/2; } +static void Snapshots(void) +{ + CHECK(GameStart(0));player.angle=359; + objtype *actor=SpawnActor(3,3,&teststand);CHECK(actor);unsigned slot=(unsigned)(actor-objlist); + doornum=1;doorobjlist[0].position=1000; + WL_PresentReset();WL_PresentCapture(100); + int32_t x=player.x,ax=actor->x;uint64_t identity=WL_PresentCurrent()->actors[slot].identity; + player.x+=4096;player.angle=1;actor->x+=4096;doorobjlist[0].position=3000;++gamestate.TimeCount;WL_PresentCapture(101); + wl_present_snapshot *sample=malloc(sizeof(*sample));CHECK(sample); + uint32_t immutable=Hash(WL_PresentCurrent(),sizeof(*sample)); + CHECK(WL_PresentSample(Half(101),sample)); + CHECK(abs(sample->camera.x-x-2048)<=1 && (sample->camera.angle<0.00001 || sample->camera.angle>359.99999)); + CHECK(abs(sample->actors[slot].x-ax-2048)<=1 && abs((int)sample->doors[0].position-2000)<=1); + CHECK(Hash(WL_PresentCurrent(),sizeof(*sample))==immutable); + RemoveActor(actor);objtype *replacement=GetNewActor();CHECK(replacement==actor);replacement->state=&teststand; + replacement->x=ax+32768;replacement->y=3*TILEGLOBAL;replacement->dir=0; + ++gamestate.TimeCount;WL_PresentCapture(102);CHECK(WL_PresentSample(Half(102),sample)); + CHECK(sample->actors[slot].identity!=identity && sample->actors[slot].x==replacement->x); + pwallstate=127;pwallpos=63;pwallx=4;pwally=4;pwalldir=0;tilemap[4][4]=0xc1;tilemap[5][4]=1; + WL_PresentCapture(103);pwallstate=128;pwallpos=0;pwallx=5;tilemap[4][4]=0;tilemap[5][4]=0xc1; + WL_PresentCapture(104);CHECK(WL_PresentSample(Half(104),sample)); + CHECK(sample->push_x==4 && sample->tiles[4][4]==0xc1 && abs(sample->push_offset-65024)<=1); + CHECK(WL_PresentSample(WL_TickNS(105),sample) && sample->push_offset==0 && sample->tiles[5][4]==0xc1); + player.x+=3*TILEGLOBAL;WL_PresentCapture(105);CHECK(WL_PresentSample(Half(105),sample) && sample->camera.x==player.x); + GamePauseClock(200);CHECK(WL_PresentSample(WL_TickNS(200),sample) && sample->camera.x==player.x); + CHECK(GameStart(0) && Save_Write(5,"snapshot reset",true)); + CT_Key(SDL_SCANCODE_UP,true);CHECK(GameStep(10));CT_Key(SDL_SCANCODE_UP,false); + CHECK(Save_Load(5,300) && WL_PresentSample(WL_TickNS(300),sample));CHECK(sample->camera.x==player.x && sample->camera.y==player.y); + CHECK(GameStartMap(0,1,2,0));CHECK(WL_PresentSample(0,sample) && sample->level==1 && sample->camera.x==player.x); + CHECK(GameStart(0));player.angle=0;objtype attacker=player;attacker.y-=TILEGLOBAL;TakeDamage(1000,&attacker); + CHECK(GameStep(1) && GameStep(2));CHECK(WL_PresentSample(Half(2),sample));CHECK(fabs(sample->camera.angle-3)<0.00001); + uint64_t death_tick=2; + while(gamestate.died && death_tick<600) CHECK(GameStep(++death_tick)); + CHECK(!gamestate.died && WL_PresentSample(WL_TickNS(death_tick)+1000000,sample)); + CHECK(sample->camera.x==player.x && sample->camera.y==player.y && sample->camera.angle==player.angle); + CHECK(GameStart(0));WL_PresentCapture(390);player.x+=4096;CHECK(NewViewSize(16)); + WL_PresentCapture(391);CHECK(WL_PresentSample(Half(391),sample) && sample->camera.x==player.x); + CHECK(NewViewSize(15)); + /* Unmatched doors must snap, even when an index was reused. */ + CHECK(GameStart(0));doornum=1;doorobjlist[0]=(doorobj_t){4,4,0,true,dr_opening,1000,0}; + WL_PresentReset();WL_PresentCapture(400); + doornum=2;doorobjlist[1]=(doorobj_t){5,4,0,true,dr_opening,3000,0}; + doorobjlist[0].x=6;doorobjlist[0].position=5000;WL_PresentCapture(401); + CHECK(WL_PresentSample(Half(401),sample)); + CHECK(sample->doors[0].position==5000 && sample->doors[1].position==3000); + /* Only pushwall cells rewind; a door opening in this tick stays floor. */ + tilemap[8][8]=128;pwallstate=127;pwallpos=63;pwallx=4;pwally=4;pwalldir=0; + tilemap[4][4]=0xc1;tilemap[5][4]=1;tilemap[6][4]=0;WL_PresentCapture(402); + tilemap[8][8]=0;tilemap[6][4]=1;pwallstate=128;pwallpos=0;pwallx=5;tilemap[4][4]=0;tilemap[5][4]=0xc1; + WL_PresentCapture(403);CHECK(WL_PresentSample(Half(403),sample)); + CHECK(sample->tiles[8][8]==0 && sample->tiles[4][4]==0xc1 && sample->tiles[6][4]==0); + /* Unrelated pushwalls and actor teleports never connect across space. */ + pwallx=10;pwallpos=10;WL_PresentCapture(404);CHECK(WL_PresentSample(Half(404),sample)); + CHECK(sample->push_x==10 && sample->push_offset==10240); + actor=SpawnActor(3,3,&teststand);CHECK(actor);slot=(unsigned)(actor-objlist); + actor->dir=7;WL_PresentCapture(405);actor->dir=0;WL_PresentCapture(406); + CHECK(WL_PresentSample(Half(406),sample) && fabs(sample->actors[slot].facing-337.5)<0.001); + actor->x+=3*TILEGLOBAL;WL_PresentCapture(407);CHECK(WL_PresentSample(Half(407),sample)); + CHECK(sample->actors[slot].x==actor->x); + RemoveActor(actor);WL_PresentCapture(408);CHECK(WL_PresentSample(Half(408),sample)); + CHECK(!sample->actors[slot].identity); + const int dx[4]={1,0,-1,0},dy[4]={0,-1,0,1}; + for(unsigned direction=0;direction<4;++direction) { + int nx=20+dx[direction],ny=20+dy[direction],fx=nx+dx[direction],fy=ny+dy[direction]; + pwallx=20;pwally=20;pwalldir=(int)direction*2;pwallstate=127;pwallpos=63; + tilemap[20][20]=0xc1;tilemap[nx][ny]=1;tilemap[fx][fy]=0; + WL_PresentReset();WL_PresentCapture(500); + pwallx=nx;pwally=ny;pwallstate=128;pwallpos=0; + tilemap[20][20]=0;tilemap[nx][ny]=0xc1;tilemap[fx][fy]=1;WL_PresentCapture(501); + CHECK(WL_PresentSample(Half(501),sample)); + CHECK(sample->push_x==20 && sample->push_y==20 && sample->tiles[20][20]==0xc1); + CHECK(sample->tiles[nx][ny]==1 && sample->tiles[fx][fy]==0); + CHECK(WL_PresentSample(WL_TickNS(502)+1,sample) && sample->push_x==nx && sample->tiles[fx][fy]==1); + pwallstate=255;pwallpos=63;WL_PresentCapture(502); + pwallstate=0;tilemap[nx][ny]=0;WL_PresentCapture(503); + CHECK(WL_PresentSample(Half(503),sample) && sample->tiles[nx][ny]==0xc1 && abs(sample->push_offset-65024)<=1); + CHECK(WL_PresentSample(WL_TickNS(504)+1,sample) && sample->tiles[nx][ny]==0); + } + GameStop();CHECK(!WL_PresentSample(0,sample));free(sample); + puts("Immutable poses, angle wrap, actor reuse, doors, pushwall crossings, teleport, pause, load, level and death resets passed."); +} +static void Images(void) +{ + uint8_t *pixels=malloc(640*480);wl_present_snapshot *sample=malloc(sizeof(*sample));CHECK(pixels && sample); + wl_render_target target;int32_t depth[640];CHECK(WL_TargetInit(&target,pixels,640*480,640,480,640)); + CT_Reset(CT_CLASSIC);CHECK(GameStart(0));CT_Key(SDL_SCANCODE_RIGHT,true);CHECK(GameStep(1) && GameStep(2)); + uint32_t images[3],before=State();uint64_t times[]={WL_TickNS(2),Half(2),WL_TickNS(3)}; + for(unsigned i=0;i<3;++i) { CHECK(WL_PresentSample(times[i],sample));CHECK(WL_RenderSnapshot(&target,depth,640,true,16,9,sample,NULL));images[i]=Hash(pixels,640*480); } + CHECK(images[0]!=images[1] && images[1]!=images[2] && State()==before); + objtype saved=player;w3r_byte tiles[64][64];doorobj_t doors[64];memcpy(tiles,tilemap,sizeof(tiles));memcpy(doors,doorobjlist,sizeof(doors)); + unsigned door_count=doornum,statics=statcount,offset=pwallpos; + player.angle=999;player.next=NULL;memset(tilemap,1,sizeof(tilemap));doornum=statcount=0;pwallpos=63; + CHECK(WL_RenderSnapshot(&target,depth,640,true,16,9,sample,NULL));CHECK(Hash(pixels,640*480)==images[2]); + player=saved;memcpy(tilemap,tiles,sizeof(tiles));memcpy(doorobjlist,doors,sizeof(doors));doornum=door_count;statcount=statics;pwallpos=offset;CHECK(State()==before); + sample->camera.angle=NAN;CHECK(!WL_RenderSnapshot(&target,depth,640,true,16,9,sample,NULL)); + CHECK(GameStart(0));player.x=2*TILEGLOBAL+32768;player.y=3*TILEGLOBAL+32768;player.angle=0;player.next=NULL;statcount=0; + memset(tilemap,0,sizeof(tilemap));for(unsigned i=0;i<64;++i) tilemap[0][i]=tilemap[63][i]=tilemap[i][0]=tilemap[i][63]=1; + for(unsigned y=1;y<63;++y) tilemap[4][y]=1; + tilemap[4][3]=128;doornum=1;doorobjlist[0]=(doorobj_t){4,3,0,true,dr_opening,0,0}; + WL_PresentReset();WL_PresentCapture(200);doorobjlist[0].position=65535;WL_PresentCapture(201); + for(unsigned i=0;i<3;++i) { uint64_t t=i==0?WL_TickNS(201):i==1?Half(201):WL_TickNS(202);CHECK(WL_PresentSample(t,sample));CHECK(WL_RenderSnapshot(&target,depth,640,true,16,9,sample,NULL));images[i]=Hash(pixels,640*480); } + CHECK(images[0]!=images[1] && images[1]!=images[2]); + tilemap[4][3]=0xc1;pwallstate=1;pwallpos=0;pwallx=4;pwally=3;pwalldir=0;WL_PresentReset();WL_PresentCapture(210); + pwallpos=32;WL_PresentCapture(211); + for(unsigned i=0;i<3;++i) { uint64_t t=i==0?WL_TickNS(211):i==1?Half(211):WL_TickNS(212);CHECK(WL_PresentSample(t,sample));CHECK(WL_RenderSnapshot(&target,depth,640,true,16,9,sample,NULL));images[i]=Hash(pixels,640*480); } + CHECK(images[0]!=images[1] && images[1]!=images[2]); + free(pixels);free(sample);GameStop();puts("Intermediate camera, door and pushwall images are distinct; snapshot rays ignore the mutable live world."); +} +static void Rates(const char *directory) +{ + static const unsigned rates[]={60,75,90,120,144,165,180,240}; + uint8_t *pixels=malloc(640*480);wl_present_snapshot *sample=malloc(sizeof(*sample));CHECK(pixels && sample); + wl_render_target target;int32_t depth[640];CHECK(WL_TargetInit(&target,pixels,640*480,640,480,640)); + for(unsigned r=0;r +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"Benchmark failed: %s (%s)\n",#x,CA_Error());exit(1); } } while(0) +int main(int argc,char **argv) +{ + CHECK(argc==2);MM_Startup();CHECK(CA_Startup(argv[1])); + CHECK(GameStart(0) && NewViewSize(19) && GameDrawPaused()); + static const unsigned sizes[][2]={{640,480},{1280,720},{1920,1080},{3440,1440},{3840,1080},{4096,2160}}; + for(unsigned n=0;n +#include +static unsigned Hash(const unsigned char *p,size_t n) +{ unsigned h=2166136261U;while(n--) h=(h^*p++)*16777619U;return h; } +int main(int argc,char **argv) +{ + if(argc!=2) return 2; + MM_Startup();if(!CA_Startup(argv[1])) return 2; + const unsigned sizes[][2]={{640,480},{1280,720},{1920,1080},{1920,803},{1920,540}}; + const unsigned aspects[][2]={{4,3},{16,9},{16,10},{21,9},{32,9}}; + unsigned char *pixels=malloc(1920*1080);int32_t depth[1920]; + if(!pixels) return 2; + for(unsigned map=0;map<60;++map) { + if(!GameStartMap(0,map,2,0)) return 2; + for(unsigned n=0;n<5;++n) for(unsigned a=0;a<5;++a) { + if(!NewViewSize(n%2?4:19)) return 2; + player.angle=(int)((map*37+a*71)%360); + if(!GameDrawPaused()) return 2; + wl_render_target t; + if(!WL_TargetInit(&t,pixels,1920*1080,sizes[n][0],sizes[n][1],sizes[n][0]) || + !WL_RenderFrameAspect(&t,depth,1920,true,aspects[a][0],aspects[a][1],NULL)) return 2; + printf("%u,%u,%u,%u\n",map,n,a,Hash(pixels,(size_t)t.width*t.height)); + } + } + free(pixels);GameStop();CA_Shutdown();MM_Shutdown();return MM_TotalBytes()?2:0; +} diff --git a/tests/render_original_tests.c b/tests/render_original_tests.c new file mode 100644 index 00000000..11c4572c --- /dev/null +++ b/tests/render_original_tests.c @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Capture the untouched indexed DOS framebuffer at every supported view size. */ +#include "engine/WL_DEF.h" +#include "engine/WL_SAVE.h" +#include "engine/ID_CA.h" +#include "engine/ID_VL.h" +#include +static unsigned Hash(void) { unsigned h=2166136261U;for(unsigned i=0;i +#include +#include +int main(void) +{ + uint8_t pixels[4*6];memset(pixels,0xaa,sizeof(pixels)); + wl_render_target t={0}; + assert(!WL_TargetInit(&t,pixels,sizeof(pixels),0,4,6)); + assert(!WL_TargetInit(&t,pixels,sizeof(pixels),5,4,4)); + assert(!WL_TargetInit(&t,pixels,sizeof(pixels)-1,4,4,6)); + assert(!WL_TargetInit(&t,pixels,sizeof(pixels),UINT32_MAX,UINT32_MAX,UINT32_MAX)); + assert(WL_TargetInit(&t,pixels,sizeof(pixels),4,4,6)); + assert(WL_TargetClear(&t,7)); + for(unsigned y=0;y<4;++y) for(unsigned x=0;x<6;++x) + assert(pixels[y*6+x]==(x<4?7:0xaa)); + assert(!WL_TargetPixel(&t,4,0,1)); + assert(!WL_TargetPixel(&t,0,4,1)); + assert(WL_TargetPixel(&t,3,3,9)); + assert(pixels[3*6+3]==9); + wl_render_target valid=t; + assert(!WL_TargetInit(&t,NULL,0,4,4,6) && !memcmp(&t,&valid,sizeof(t))); + t.stride=1;assert(!WL_TargetClear(&t,0) && !WL_TargetPixel(&t,1,1,0));t=valid; + t.capacity=1;assert(!WL_TargetClear(&t,0) && !WL_TargetPixel(&t,0,0,0));t=valid; + t.height=UINT32_MAX;assert(!WL_TargetClear(&t,0) && !WL_TargetPixel(&t,0,0,0)); + assert(!WL_TargetPixel(NULL,0,0,0) && !WL_TargetClear(NULL,0)); + return 0; +} diff --git a/tests/render_tests.c b/tests/render_tests.c new file mode 100644 index 00000000..8ec02db4 --- /dev/null +++ b/tests/render_tests.c @@ -0,0 +1,441 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_RENDER.h" +#include "engine/WL_SAVE.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_DISPLAY.h" +#include "engine/ID_CA.h" +#include "engine/ID_VL.h" +#include "engine/ID_PM.h" +#include "engine/ID_US_1.h" +#include "platform/sdl_video.h" +#include "platform/sdl_audio.h" +#include "engine/ID_SD.h" +#include "platform/config_file.h" +#include +#include +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s; %s)\n",__LINE__,#x,CA_Error(),SDL_GetError());exit(1); } } while(0) +#include "finish_loading.h" +static uint32_t Hash(const void *data,size_t n) { const unsigned char *p=data;uint32_t h=2166136261U;while(n--) h=(h^*p++)*16777619U;return h; } +static void Pump(void) { CHECK(!VL_PollQuit());CHECK(VW_UpdateScreen()); } +/* Force long frames without stalling any individual rendering batch. The + real dummy device drains concurrently, so servicing only once per frame + would empty the 24-32 ms queue. */ +static bool with_audio; +static unsigned services,empty; +static uint64_t last_service,max_gap; +static void ServiceAudio(void) +{ + SDL_Delay(1); + uint64_t now=SDL_GetTicksNS(),gap=now-last_service; + if(gap>max_gap) max_gap=gap; + last_service=now; + if(!Audio_TestQueuedBytes()) ++empty; + CHECK(Audio_TestQueuedBytes()>=0);Audio_Pump();++services; +} +static void AudioStress(void) +{ + CHECK(Audio_Startup());SD_StartMusic(7);Audio_Pump(); + unsigned policy=Audio_TestTargetMS();CHECK(policy>=80 && policy<=250); + Audio_TestQueueMS(24);Audio_Pump();SDL_Delay(60);int short_queue=Audio_TestQueuedBytes(); + Audio_TestQueueMS(policy);Audio_Pump();SDL_Delay(60);int safe_queue=Audio_TestQueuedBytes(); + CHECK(short_queue==0 && safe_queue>0); + printf("Audio 60 ms stall: 24 ms policy %d bytes, %u ms policy %d bytes remaining.\n",short_queue,policy,safe_queue); + Audio_Pump(); + int queued_ahead=Audio_TestQueuedBytes();CHECK(queued_ahead>0); + CHECK(SD_PlaySound(ATKPISTOLSND,0,0)); + printf("Effect request: %.2f ms already queued before synthesis (device/OS latency additional).\n",(double)queued_ahead/192.0); + uint8_t *pixels=malloc(1920*1080);int32_t depth[1920];wl_render_target t; + CHECK(pixels && WL_TargetInit(&t,pixels,1920*1080,1920,1080,1920)); + CHECK(NewViewSize(19));last_service=SDL_GetTicksNS();uint64_t start=last_service; + for(unsigned i=0;i<3;++i) CHECK(WL_RenderFrame(&t,depth,1920,true,ServiceAudio)); + CHECK(services>300 && SDL_GetTicksNS()-start>32000000); + CHECK(!empty); /* No drained queue despite frames longer than its capacity. */ + sd_status status;SD_GetStatus(&status);CHECK(status.frames>48000/10); + printf("Audio render stress: %u services, %u empty queues, longest gap %.2f ms.\n",services,empty,(double)max_gap/1000000); + free(pixels);Audio_Shutdown();CHECK(NewViewSize(15)); +} +/* Synthetic desktop modes exercise the production Auto replacement path; + SDL's real output remains independently sized. No physical monitor claim. */ +static void AutoScaling(const char *directory) +{ + display_settings d;CHECK(VL_DisplayGet(&d)); + d.high_resolution=true;d.smooth=false;d.render_auto=true;d.aspect=2; + d.linear=d.integer=d.vsync=false;d.scale=0;d.width=3840;d.height=2160; + VL_TestDesktopSize(3840,2160);CHECK(VL_DisplaySet(&d));Pump(); + uint64_t creations=VL_TestSurfaceCreations(); + SDL_Texture *texture=VL_TestSceneTexture();float w,h; + CHECK(texture && SDL_GetTextureSize(texture,&w,&h) && w==1920 && h==1080); + SDL_ScaleMode filter;CHECK(SDL_GetTextureScaleMode(texture,&filter) && filter==SDL_SCALEMODE_NEAREST); + VL_TestDesktopSize(2560,1440);Pump();CHECK(VL_TestSurfaceCreations()==creations); + CHECK(VL_TestSceneTexture()==texture); /* Same capped canvas, no allocation. */ + VL_TestDesktopSize(3440,1440);VL_TestDisplayFailure(5);Pump(); + CHECK(VL_TestSceneTexture()==texture && VL_TestSurfaceCreations()==creations); + Pump();CHECK(VL_TestSceneTexture()==texture); /* Retry is throttled. */ + VL_TestDesktopSize(3440,1440);VL_TestDisplayFailure(6);Pump(); + CHECK(VL_TestSceneTexture()==texture && VL_TestSurfaceCreations()==creations); + const unsigned modes[][4]={{3440,1440,1920,803},{3840,1080,1920,540}, + {1600,1200,1440,1080},{1280,720,1280,720},{3840,2160,1920,1080}}; + for(unsigned i=0;i synthetic 4K nearest path. */ + char path[4096];CHECK(snprintf(path,sizeof(path),"%s/auto-4k.bmp",directory)>0); + CHECK(VL_Capture(path));SDL_Surface *bmp=SDL_LoadBMP(path);CHECK(bmp); + SDL_Surface *image=SDL_ConvertSurface(bmp,SDL_PIXELFORMAT_RGBA32);SDL_DestroySurface(bmp); + CHECK(image); + bool exact_4k=image->w==3840 && image->h==2160; + CHECK(strcmp(SDL_GetCurrentVideoDriver(),"dummy") || exact_4k); + if(!exact_4k) printf("Exact 4K pixel check unavailable: capture is %dx%d (window-manager limit).\n",image->w,image->h); + unsigned char *pixels=malloc(1920*1080);int32_t depth[1920];wl_render_target t; + CHECK(pixels && WL_TargetInit(&t,pixels,1920*1080,1920,1080,1920)); + CHECK(WL_RenderFrameAspect(&t,depth,1920,true,16,9,NULL)); + for(unsigned y=0;exact_4k && y<2160;++y) for(unsigned x=0;x<3840;++x) { + unsigned index=pixels[(y/2)*1920+x/2]; + const unsigned char *actual=(const unsigned char *)image->pixels+(size_t)y*(unsigned)image->pitch+x*4; + for(unsigned c=0;c<3;++c) { + unsigned value=palette[index*3+c];CHECK(actual[c]==((value<<2)|(value>>4))); + } + CHECK(actual[3]==255); + } + free(pixels);SDL_DestroySurface(image); + CHECK(VL_DisplayGet(&d)); + if(d.pending) { VL_TestExpireDisplayRequest();Pump();CHECK(VL_DisplayGet(&d)); } + d.linear=true;CHECK(VL_DisplaySet(&d));Pump(); + CHECK(VL_TestSurfaceCreations()==creations); + CHECK(SDL_GetTextureScaleMode(VL_TestSceneTexture(),&filter) && filter==SDL_SCALEMODE_LINEAR); + VL_TestDesktopSize(0,0);d.render_auto=false;d.linear=false;d.width=960;d.height=720; + CHECK(VL_DisplaySet(&d));Pump(); + VL_TestExpireDisplayRequest();Pump(); +} +static void Wide(void) +{ + CHECK(NewViewSize(19));CHECK(GameDrawPaused()); + uint8_t *narrow=malloc(640*480),*wide=malloc(1280*480);int32_t depth[4096];wl_render_target a,b; + CHECK(narrow && wide && WL_TargetInit(&a,narrow,640*480,640,480,640) && WL_TargetInit(&b,wide,1280*480,1280,480,1280)); + CHECK(WL_RenderFrameAspect(&a,depth,4096,true,4,3,NULL)); + CHECK(WL_RenderFrameAspect(&b,depth,4096,true,8,3,NULL)); + /* Same vertical framing and exact central pixels; extra columns are rays, + not horizontally stretched pixels. HUD is centered independently. */ + unsigned vx=(unsigned)VIEWX*2,vw=(unsigned)VIEWWIDTH*2,vy=(unsigned)VIEWY*480/200,vh=(unsigned)VIEWHEIGHT*480/200; + for(unsigned y=vy;y=ui.x+ui.width?127:framebuffer[(size_t)(y*200/ui.height)*320+(tx-ui.x)*320/ui.width]; + CHECK(t.pixels[(size_t)(ui.y+y)*t.stride+tx]==expected); + } + } + } + printf("Render benchmark %ux%u: %.2f ms/frame (ten aspect/view combinations), %zu indexed bytes.\n",sizes[n][0],sizes[n][1],(double)(SDL_GetTicksNS()-begin)/10000000,count); + for(unsigned i=0;i<16;++i) CHECK(p[count+i]==0xad); + free(p); + } + CHECK(US_RndIndex()==rng);CHECK(NewViewSize(19));CHECK(GameDrawPaused());CHECK(Hash(framebuffer,VL_PIXELS)==before); + display_settings d;CHECK(VL_DisplayGet(&d));d.high_resolution=true;d.render_auto=true;d.aspect=5;d.linear=true; + CHECK(VL_DisplaySet(&d));Pump();CHECK(VL_DisplayGet(&d) && d.render_auto && d.aspect==5 && d.linear); + CHECK(Config_Save(SDL_getenv("XDG_DATA_HOME")));Audio_Shutdown();VL_Shutdown();CHECK(VL_Startup());if(with_audio) CHECK(Audio_Startup());CHECK(Config_Load(SDL_getenv("XDG_DATA_HOME"))==CONFIG_LOADED);Pump(); + CHECK(VL_DisplayGet(&d) && d.render_auto && d.aspect==5 && d.linear); + /* VSync may be unsupported by a backend. A rejected request must leave + the preference and all other settings unchanged. */ + d.vsync=true;bool accepted=VL_DisplaySet(&d);CHECK(VL_DisplayGet(&d));CHECK(d.vsync==accepted); + d.vsync=!d.vsync;VL_TestDisplayFailure(7);CHECK(!VL_DisplaySet(&d));CHECK(VL_DisplayGet(&d) && d.vsync==accepted); + d.linear=!d.linear;VL_TestDisplayFailure(8);CHECK(!VL_DisplaySet(&d));CHECK(VL_DisplayGet(&d) && d.linear); + /* Auto dimensions are staged before committing a display change too. */ + d.render_auto=false;d.render_width=640;d.render_height=480;d.vsync=false;CHECK(VL_DisplaySet(&d));Pump(); + d.render_auto=true;VL_TestDisplayFailure(5);CHECK(!VL_DisplaySet(&d));CHECK(VL_DisplayGet(&d) && !d.render_auto);Pump(); + CHECK(VL_Screenshot()); + SDL_Event key;SDL_zero(key);key.type=SDL_EVENT_WINDOW_FOCUS_GAINED;CHECK(SDL_PushEvent(&key));Pump(); + SDL_zero(key);key.type=SDL_EVENT_KEY_DOWN;key.key.scancode=SDL_SCANCODE_F12;CHECK(SDL_PushEvent(&key));Pump(); + key.key.repeat=true;CHECK(SDL_PushEvent(&key));Pump();key.type=SDL_EVENT_KEY_UP;CHECK(SDL_PushEvent(&key));Pump(); + CHECK(US_RndIndex()==rng);free(narrow);free(wide);CHECK(NewViewSize(15));CHECK(GameDrawPaused()); +} +static void DeathFrame(wl_render_target *t,unsigned aw,unsigned ah,unsigned expected) +{ + int32_t depth[1920];uint32_t seed,before=Hash(framebuffer,VL_PIXELS),clock=gamestate.TimeCount; + unsigned phase=GameDeathPresentation(&seed),rng=US_RndIndex();int angle=player.angle; + CHECK(phase==expected && WL_RenderFrameAspect(t,depth,1920,true,aw,ah,NULL)); + CHECK(before==Hash(framebuffer,VL_PIXELS) && clock==gamestate.TimeCount && rng==US_RndIndex() && angle==player.angle); + uint32_t after;CHECK(GameDeathPresentation(&after)==phase && after==seed); + wl_rectangle r;CHECK(WL_AspectFit(t->width,t->height,aw,ah,&r)); + unsigned vx=r.x+(unsigned)VIEWX*r.width/320,vy=r.y+(unsigned)VIEWY*r.height/200; + unsigned right=r.x+((unsigned)VIEWX+VIEWWIDTH)*r.width/320,bottom=r.y+((unsigned)VIEWY+VIEWHEIGHT)*r.height/200; + /* This lies outside the former 4:3 world rectangle in widescreen. The + scene must remain geometry (or fizzle red), never the old teal border. */ + CHECK(t->pixels[(size_t)(vy+1)*t->stride+vx+1]!=127); + if(phase==3) for(unsigned y=vy;ypixels[(size_t)y*t->stride+x]==4); + Pump(); + int n;SDL_Window **windows=SDL_GetWindows(&n);CHECK(windows && n==1); + SDL_FRect rect;CHECK(SDL_GetRenderLogicalPresentationRect(SDL_GetRenderer(windows[0]),&rect));SDL_free(windows); + CHECK(fabs((double)rect.w*ah-(double)rect.h*aw)<(double)(aw+ah)); +} +static void DeathContinuity(void) +{ + static const unsigned sizes[][2]={{640,480},{1280,720},{1920,1080}}; + static const unsigned ratios[][2]={{4,3},{16,9},{16,10},{21,9},{32,9},{16,9}}; + uint8_t *pixels=malloc(1920*1080);CHECK(pixels);unsigned duration=0; + for(unsigned n=0;n<3;++n) for(unsigned a=0;a<6;++a) { + CHECK(NewViewSize(15) && GameStart(0));player.angle=0;CHECK(GameDrawPaused()); + display_settings d;CHECK(VL_DisplayGet(&d));d.high_resolution=true;d.render_auto=d.integer=false; + d.render_width=sizes[n][0];d.render_height=sizes[n][1];d.aspect=a==5?0:a+1;d.scale=0;d.width=1280;d.height=720;CHECK(VL_DisplaySet(&d));Pump(); + wl_render_target t;CHECK(WL_TargetInit(&t,pixels,1920*1080,sizes[n][0],sizes[n][1],sizes[n][0])); + objtype attacker=player;attacker.y-=TILEGLOBAL;TakeDamage(1000,&attacker);CHECK(gamestate.died); + uint64_t tic=1;CHECK(GameStep(tic));DeathFrame(&t,ratios[a][0],ratios[a][1],1); + while(GameDeathPresentation(NULL)<2 && tic<100) CHECK(GameStep(++tic)); + DeathFrame(&t,ratios[a][0],ratios[a][1],2); + for(unsigned i=0;i<10;++i) CHECK(GameStep(++tic)); + DeathFrame(&t,ratios[a][0],ratios[a][1],2); + /* A red Classic source can stay byte-identical while the native + fizzle cursor advances. It still needs a new native upload. */ + for(unsigned y=0;y=100); /* original weapon art stays in the lower center */ + CHECK(background!=10 && background!=20); + free(pixels);GameStop(); +} +extern statetype s_grdstand; +static void BaselineWrite(const char *directory,const char *name,const uint8_t *pixels, + unsigned width,unsigned height,unsigned stride) +{ + char path[4096];CHECK(snprintf(path,sizeof(path),"%s/%s.w3i",directory,name)>0); + FILE *file=fopen(path,"wb");CHECK(file); + const uint8_t header[16]={'W','3','R','I',1,0,0,0, + (uint8_t)width,(uint8_t)(width>>8),(uint8_t)(width>>16),(uint8_t)(width>>24), + (uint8_t)height,(uint8_t)(height>>8),(uint8_t)(height>>16),(uint8_t)(height>>24)}; + CHECK(fwrite(header,1,sizeof(header),file)==sizeof(header)); + for(unsigned y=0;yangle=180;actor->dir=west;actor->active=true; + doornum=1;tilemap[9][3]=128;doorobjlist[0]=(doorobj_t){9,3,0,true,dr_closed,0,0}; + ResetPushwalls(); +} +static void BaselinePair(const char *directory,const char *stem) +{ + char name[128];CHECK(GameDrawPaused()); + CHECK(snprintf(name,sizeof(name),"%s-classic-320x200",stem)>0);BaselineWrite(directory,name,framebuffer,320,200,320); + CHECK(snprintf(name,sizeof(name),"%s-enhanced-1280x720-16x9",stem)>0);BaselineEnhanced(directory,name,1280,720,16,9); +} +static void Baselines(const char *directory) +{ + char path[4096];CHECK(snprintf(path,sizeof(path),"%s/palette.rgb6",directory)>0); + FILE *file=fopen(path,"wb");CHECK(file && fwrite(palette,1,768,file)==768 && !fclose(file)); + + BaselineScene();BaselinePair(directory,"corridor-static"); + BaselineClassicOutput(directory,"corridor-static-classic-output-640x480",640,480); + BaselineClassicOutput(directory,"corridor-static-classic-output-1280x720",1280,720); + BaselineClassicOutput(directory,"corridor-static-classic-output-1001x601",1001,601); + BaselineEnhanced(directory,"corridor-static-enhanced-640x480-4x3",640,480,4,3); + BaselineEnhanced(directory,"corridor-static-enhanced-1280x800-16x10",1280,800,16,10); + BaselineEnhanced(directory,"corridor-static-enhanced-1680x720-21x9",1680,720,21,9); + BaselineEnhanced(directory,"corridor-static-enhanced-2560x720-32x9",2560,720,32,9); + BaselineEnhanced(directory,"corridor-static-enhanced-1001x601-auto",1001,601,1001,601); + GameStop(); + + static const uint16_t door_positions[]={0,32768,65535}; + static const char *door_names[]={"closed","half-open","open"}; + for(unsigned i=0;i<3;++i) { BaselineScene();doorobjlist[0].position=door_positions[i];doorobjlist[0].action=i==2?dr_open:dr_opening; + char stem[64];CHECK(snprintf(stem,sizeof(stem),"door-motion-%s",door_names[i])>0);BaselinePair(directory,stem);GameStop(); } + + static const unsigned wall_states[]={0,32,0}; + static const char *wall_names[]={"initial","moving","tile-boundary"}; + for(unsigned i=0;i<3;++i) { BaselineScene();doornum=0;tilemap[9][3]=0; + pwallstate=i==2?128:i==1?64:1;pwallpos=wall_states[i];pwallx=i==2?9:8;pwally=3;pwalldir=east; + tilemap[8][3]=i==2?0:0xc1;tilemap[9][3]=i==2?0xc1:1;tilemap[10][3]=i==2?1:0; + char stem[64];CHECK(snprintf(stem,sizeof(stem),"pushwall-motion-%s",wall_names[i])>0);BaselinePair(directory,stem);GameStop(); } + + BaselineScene();statobjlist[0].tilex=4;statobjlist[0].tiley=1;statobjlist[1].tilex=4;statobjlist[1].tiley=5; + BaselinePair(directory,"edge-clipping");GameStop(); + + BaselineScene();CHECK(GameDrawPaused()); + BaselineClassicOutput(directory,"display-transition-classic-initial-640x480",640,480); + BaselineClassicOutput(directory,"display-transition-classic-letterbox-1280x720",1280,720); + BaselineClassicOutput(directory,"display-transition-classic-resize-1001x601",1001,601); + BaselineClassicOutput(directory,"display-transition-classic-restored-640x480",640,480); + BaselineEnhanced(directory,"display-transition-enhanced-initial-640x480-4x3",640,480,4,3); + BaselineEnhanced(directory,"display-transition-enhanced-wide-1280x720-16x9",1280,720,16,9); + BaselineEnhanced(directory,"display-transition-enhanced-auto-1001x601",1001,601,1001,601); + BaselineEnhanced(directory,"display-transition-enhanced-restored-640x480-4x3",640,480,4,3); + GameStop();puts("Synthetic Classic/Enhanced visual baselines captured."); +} +int main(int argc,char **argv) +{ + CHECK(argc==4); + const float rates[]={60,75,90,120,144,165,180,240,73,59.94f}; + for(unsigned i=0;i=4 && ph>=3) { SDL_FRect rect;CHECK(SDL_GetRenderLogicalPresentationRect(SDL_GetRenderer(window),&rect));CHECK(fabs(rect.w*3-rect.h*4)<=4); } + } + d.fullscreen=true;CHECK(VL_DisplaySet(&d) && SDL_SyncWindow(window));Pump(); + CHECK(VL_DisplayGet(&d) && d.fullscreen);d.fullscreen=false;CHECK(VL_DisplaySet(&d) && SDL_SyncWindow(window));Pump(); + } + CHECK(!memcmp(&player,&saved_player,sizeof(player)) && !memcmp(saved_actors,objlist,sizeof(saved_actors))); + CHECK(!memcmp(saved_vis,spotvis,sizeof(saved_vis)) && Hash(framebuffer,VL_PIXELS)==frame); + CHECK(Save_Write(1,"render after",true)); + /* Failed allocations/resolutions/fullscreen requests retain the old surface. */ + display_settings d,old;CHECK(VL_DisplayGet(&old));d=old;d.render_width=1234;CHECK(!VL_DisplaySet(&d)); + d=old;d.render_width=640;d.render_height=480;VL_TestDisplayFailure(5);CHECK(!VL_DisplaySet(&d));Pump(); + CHECK(VL_DisplayGet(&d) && d.render_width==old.render_width && d.high_resolution); + d=old;d.render_width=640;d.render_height=480;VL_TestDisplayFailure(6);CHECK(!VL_DisplaySet(&d));Pump(); + d=old;d.high_resolution=false;d.fullscreen=true;VL_TestDisplayFailure(1);CHECK(!VL_DisplaySet(&d));Pump(); + CHECK(VL_DisplayGet(&d) && d.high_resolution); + /* Switching display preference cannot consume a simulation tic or RNG. */ + for(unsigned n=0;n<30;++n) { d.high_resolution=!d.high_resolution;CHECK(VL_DisplaySet(&d));Pump();CHECK(US_RndIndex()==rng && gamestate.TimeCount==clock); } + Wide();AutoScaling(argv[2]);DeathContinuity(); + if(!strcmp(argv[3],"synthetic")) { Visual();const char *baseline=getenv("WOLF3D_BASELINE_DIR");if(baseline) Baselines(baseline); } + else { AudioStress();OwnedLevels(); } + GameStop();Audio_Shutdown();Display_Connect(NULL,NULL);VL_Shutdown();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); + puts("Native render targets, all sizes/views, HUD, isolation, persistence, switching and failure recovery passed.");return 0; +} diff --git a/tests/save_sdl_tests.c b/tests/save_sdl_tests.c new file mode 100644 index 00000000..c607822f --- /dev/null +++ b/tests/save_sdl_tests.c @@ -0,0 +1,81 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_SAVE.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_MENU.h" +#include "engine/ID_CA.h" +#include "engine/ID_SD.h" +#include "platform/sdl_video.h" +#include "platform/sdl_audio.h" +#include "platform/save_file.h" +#include +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s; %s)\n",__LINE__,#x,CA_Error(),Audio_Error());exit(1); } } while(0) +#include "finish_loading.h" +static uint64_t ticks; +static void Step(void) { CHECK(!VL_PollQuit());CHECK(DemoLoop(++ticks));if(GameLoading()) TestFinishLoading(ticks);Audio_Pump();CHECK(VW_UpdateScreen()); } +static void Steps(unsigned n) { while(n--) Step(); } +static void Tap(SDL_Scancode code) +{ + SDL_Event e={0};e.key.scancode=code;e.type=SDL_EVENT_KEY_DOWN;CHECK(SDL_PushEvent(&e)); + e.type=SDL_EVENT_KEY_UP;CHECK(SDL_PushEvent(&e));Step(); +} +static void Menu(int choice) { MainItems.curpos=choice;Tap(SDL_SCANCODE_RETURN);Steps(23); } +static void Capture(const char *name) +{ + const char *dir=getenv("WOLF3D_CAPTURE_DIR");if(!dir) return; + char path[4096];(void)snprintf(path,sizeof(path),"%s/%s.bmp",dir,name);CHECK(VL_Capture(path)); +} +int main(int argc,char **argv) +{ + CHECK(argc==4);MM_Startup();CHECK(CA_Startup(argv[1]));CHECK(VL_Startup()); + SD_SetDigitizedMode(true);CHECK(Audio_Startup()); + char savepath[4096];(void)snprintf(savepath,sizeof(savepath),"%s%s",argv[2],getenv("WOLF3D_TEST_UNICODE")?"/\xc3\xa9":""); + CHECK(SDL_CreateDirectory(savepath));CHECK(Save_SetDirectory(savepath)); + CHECK(GameProbe());MainMenu[newgame].active=1;MainItems.curpos=newgame; + CHECK(DemoLoopStartup(0,true));Steps(11); + if(!strcmp(argv[3],"read")) { + Menu(loadgame);CHECK(DemoLoopState()==UI_LOAD);Tap(SDL_SCANCODE_RETURN);Steps(23); + CHECK(DemoLoopState()==UI_GAME && GameRunning() && gamestate.score==8842 && gamestate.health==76 && gamestate.ammo==62); + sd_status audio;SD_GetStatus(&audio);CHECK(audio.music==SD_LevelMusic(0,0)); + } else { + CHECK(DemoLoopStartGame(ticks));Steps(11); + gamestate.score=8842;gamestate.health=76;gamestate.ammo=62; + Tap(SDL_SCANCODE_ESCAPE);Steps(23);CHECK(DemoLoopState()==UI_MENU && GameRunning() && CA_Map()); + uint32_t clock=gamestate.TimeCount;Steps(70);CHECK(gamestate.TimeCount==clock); + Menu(savegame);CHECK(DemoLoopState()==UI_SAVE);Capture("save-slots"); + Tap(SDL_SCANCODE_RETURN);Tap(SDL_SCANCODE_A);Tap(SDL_SCANCODE_1);Capture("save-description"); + Tap(SDL_SCANCODE_RETURN);Steps(23);CHECK(DemoLoopState()==UI_MENU); + save_info info;Save_ReadInfo(0,&info);CHECK(info.status==SAVE_VALID && !strcmp(info.description,"a1")); + Menu(savegame);Tap(SDL_SCANCODE_RETURN);Capture("save-overwrite");Tap(SDL_SCANCODE_N); + Tap(SDL_SCANCODE_RETURN);Tap(SDL_SCANCODE_Y);Tap(SDL_SCANCODE_BACKSPACE);Tap(SDL_SCANCODE_B);Tap(SDL_SCANCODE_ESCAPE); + Save_ReadInfo(0,&info);CHECK(!strcmp(info.description,"a1")); + Tap(SDL_SCANCODE_RETURN);Tap(SDL_SCANCODE_Y);Tap(SDL_SCANCODE_B);Tap(SDL_SCANCODE_RETURN);Steps(23); + Save_ReadInfo(0,&info);CHECK(!strcmp(info.description,"a1b")); + gamestate.score=12345;Menu(loadgame);CHECK(DemoLoopState()==UI_LOAD);Capture("load-slots"); + Tap(SDL_SCANCODE_DOWN);Tap(SDL_SCANCODE_RETURN);CHECK(DemoLoopState()==UI_LOAD && gamestate.score==12345); + Tap(SDL_SCANCODE_ESCAPE);Tap(SDL_SCANCODE_UP);Tap(SDL_SCANCODE_RETURN);Steps(23); + CHECK(DemoLoopState()==UI_GAME && gamestate.score==8842 && gamestate.health==76 && gamestate.ammo==62); + Tap(SDL_SCANCODE_ESCAPE);Steps(23);Menu(loadgame);Tap(SDL_SCANCODE_ESCAPE);Steps(23); + CHECK(DemoLoopState()==UI_MENU && GameRunning()); + char path[4128];uint8_t bad[96]={0}; + CHECK(strlen(savepath) +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s)\n",__LINE__,#x,CA_Error());exit(1); } } while(0) +static void Step(unsigned start,unsigned count) +{ + for(unsigned t=start;tnext) FirstSighting(o); + T_FakeFire(&objlist[1]);DamageActor(&objlist[1],10000); + RemoveActor(&objlist[2]);T_GiftThrow(&objlist[3]);T_SchabbThrow(&objlist[0]); + CHECK(ThreeDRefresh()); + CHECK(pwallstate && doorobjlist[0].action==dr_opening && statobjlist[statcount-1].shapenum==-1); + CHECK(Save_Write(0,"moving world",true)); + Step(1,90);CHECK(Save_Write(1,"continuous",true));unsigned rng=US_RndIndex(); + CHECK(Save_Load(0,0));CHECK(gamestate.health==89 && gamestate.ammo==91 && gamestate.lives==7 && gamestate.keys==3); + CHECK(pwallstate==38 && pwallpos==19 && doorobjlist[0].position==17408 && doorobjlist[0].ticcount==304 && staticblock[40][40]); + CHECK(statobjlist[statcount-1].shapenum==-1 && gamestate.weapon==wp_chaingun && gamestate.attackframe==2); + Step(1,90);CHECK(US_RndIndex()==rng);CHECK(Save_Write(2,"restored",true)); +} +static void End(void) { GameStop();SD_Shutdown();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); } +int main(int argc,char **argv) +{ + CHECK(argc>=3);MM_Startup();CHECK(CA_Startup(argv[1]));CHECK(VL_SetPalette(gamepal,768));CHECK(Save_SetDirectory(argv[2])); + if(argc==4 && !strcmp(argv[3],"read")) { + CHECK(Save_Load(0,1000));CHECK(GameCanSave());CHECK(Save_Write(5,"restart",true));End();return 0; + } + if(argc==4 && !strcmp(argv[3],"episodes")) { + for(unsigned ep=0;ep<6;++ep) { + CHECK(GameStartSelected(0,ep,2));Step(1,20); + CHECK(Save_Write(0,"episode checkpoint",true));Step(21,40); + CHECK(Save_Write(1,"continuous",true));unsigned rng=US_RndIndex(); + CHECK(Save_Load(0,20));CHECK((unsigned)gamestate.episode==ep); + Step(21,40);CHECK(US_RndIndex()==rng);CHECK(Save_Write(2,"restored",true)); + char first[4096],second[4096];(void)snprintf(first,sizeof(first),"%s/slot2.w3s",argv[2]); + (void)snprintf(second,sizeof(second),"%s/slot3.w3s",argv[2]); + FILE *a=fopen(first,"rb"),*b=fopen(second,"rb");CHECK(a && b); + CHECK(!fseek(a,96,SEEK_SET) && !fseek(b,96,SEEK_SET)); + int x,y;do { x=fgetc(a);y=fgetc(b);CHECK(x==y); } while(x!=EOF); + CHECK(!ferror(a) && !ferror(b));CHECK(!fclose(a) && !fclose(b)); + IN_ClearKeysDown();playstate=ex_completed;CHECK(GameStep(61) && GameIntermission()); + IN_KeyEvent(sc_Enter,true);CHECK(GameStep(62)); + if(GameIntermission()) { IN_ClearKeysDown();IN_KeyEvent(sc_Enter,true);CHECK(GameStep(63)); } + CHECK(!GameIntermission() && gamestate.mapon==1 && (unsigned)gamestate.episode==ep); + } + End();return 0; + } + Start();CHECK(GameCanSave()); + if(argc==4 && !strcmp(argv[3],"scenario")) { Scenario();End();return 0; } + if(argc==4 && !strcmp(argv[3],"respawn")) { + TakeDamage(100,NULL);CHECK(!Save_Write(0,"dead",true)); + unsigned t=0;while(gamestate.died && t<1000) CHECK(GameStep(++t)); + CHECK(!gamestate.died && gamestate.lives==2);CHECK(Save_Write(0,"respawn",true)); + CHECK(Save_Load(0,t));CHECK(gamestate.health==100 && gamestate.ammo==8 && gamestate.lives==2); + End();return 0; + } + if(argc==4 && !strcmp(argv[3],"audio")) { + SD_SetDigitizedMode(true);Start();CHECK(SD_Startup(48000)); + CHECK(Save_Write(0,"with audio",true));SD_SetVolumes(22,11);SD_SetEnabled(true,false); + uint64_t generation=SD_OutputGeneration();CHECK(Save_Load(0,0)); + unsigned m,e;bool mon,eon;SD_GetSettings(&m,&e,&mon,&eon);sd_status audio;SD_GetStatus(&audio); + CHECK(m==22 && e==11 && mon && !eon && audio.sound==-1 && audio.digitized==-1); + CHECK(audio.music==SD_LevelMusic(0,0) && SD_OutputGeneration()>generation && s_schabbdie2.tictime==140); + End();return 0; + } + if(argc==4 && !strcmp(argv[3],"reject")) { + Step(1,10);CHECK(Save_Write(4,"before rejection",true));unsigned rng=US_RndIndex(); + CHECK(!Save_Load(0,500));CHECK(GameCanSave() && US_RndIndex()==rng); + CHECK(Save_Write(5,"after rejection",true));End();return 0; + } + if(argc==4 && !strcmp(argv[3],"writefail")) { CHECK(!Save_Write(0,"failed replacement",true));End();return 0; } + if(argc==4 && !strncmp(argv[3],"create",6)) { bool ok=Save_Write(0,argv[3],false);End();return ok?0:2; } + + for(unsigned i=0;inext) { objtype *gone=player.next;RemoveActor(gone);CHECK(GetNewActor()==gone);gone->obclass=inertobj;gone->state=Save_State(1);gone->x=gone->y=20*TILEGLOBAL;gone->tilex=gone->tiley=20; } + Step(1,50);CHECK(Save_Write(0,"midgame",true)); + Step(51,80);CHECK(Save_Write(1,"continuous",true));unsigned rng=US_RndIndex(); + CHECK(Save_Load(0,50));CHECK(GameCanSave());Step(51,80);CHECK(US_RndIndex()==rng);CHECK(Save_Write(2,"restored",true)); + /* The Python oracle compares the complete portable payloads. */ + for(unsigned id=0;id +#include +#include +#include +#include +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"%d: %s (%s / %s)\n",__LINE__,#x,CA_Error(),SDL_GetError());exit(1); } } while(0) +static SDL_Window *window; +static SDL_Renderer *renderer; +static unsigned resizes; +static unsigned char raw[64000],expected[64000],before[64000]; +static display_settings Settings(void) { display_settings d;CHECK(VL_DisplayGet(&d));return d; } +static void Pump(void) { CHECK(!VL_PollQuit() && VW_UpdateScreen()); } +static void Set(display_settings d) +{ + CHECK(VL_DisplaySet(&d));Uint64 deadline=SDL_GetTicks()+4000; + do { CHECK(SDL_SyncWindow(window));Pump();if(!Settings().pending) break;SDL_Delay(5); } while(SDL_GetTicks()type==SDL_EVENT_WINDOW_RESIZED || event->type==SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED) ++resizes; + return true; +} +static void Key(bool down,bool repeat) +{ + SDL_Event event={0};event.type=down?SDL_EVENT_KEY_DOWN:SDL_EVENT_KEY_UP; + event.key.scancode=SDL_SCANCODE_SPACE;event.key.repeat=repeat;CHECK(SDL_PushEvent(&event));CHECK(!VL_PollQuit()); +} +/* Independent font composition oracle, matching DOS FinishSignon's coordinates. */ +static void Prompt(const char *text,unsigned char color) +{ + memcpy(expected,raw,sizeof(raw)); + for(unsigned y=82;y<84;++y) memset(expected+y*320+164,14,12); + for(unsigned y=151;y<153;++y) memset(expected+y*320+164,14,12); + for(unsigned y=189;y<200;++y) memset(expected+y*320,raw[0],300); + CHECK(CA_CacheGrChunk(STARTFONT));const unsigned char *font=grsegs[STARTFONT]; + unsigned height=font[0]+256U*font[1],width=0; + for(const unsigned char *s=(const unsigned char *)text;*s;++s) width+=font[514+*s]; + CHECK(width<=320 && height<=10);unsigned x=(320-width)/2; + for(const unsigned char *s=(const unsigned char *)text;*s;++s) { + unsigned w=font[514+*s],at=font[2+*s*2]+256U*font[3+*s*2]; + for(unsigned y=0;y0);CHECK(VL_Capture(path)); + SDL_FRect rect;int w,h;CHECK(SDL_GetRenderOutputSize(renderer,&w,&h)); + CHECK(SDL_GetRenderLogicalPresentationRect(renderer,&rect)); + double scale=fmin((double)w/320,(double)h/240); + CHECK(fabs(rect.w-320*scale)<=1 && fabs(rect.h-240*scale)<=1); + CHECK(fabs(rect.x-((double)w-rect.w)/2)<=1 && fabs(rect.y-((double)h-rect.h)/2)<=1); + int lw,lh;SDL_RendererLogicalPresentation mode; + CHECK(SDL_GetRenderLogicalPresentation(renderer,&lw,&lh,&mode)); + CHECK(lw==320 && lh==240 && mode==SDL_LOGICAL_PRESENTATION_LETTERBOX); + CHECK(SDL_SetRenderLogicalPresentation(renderer,0,0,SDL_LOGICAL_PRESENTATION_DISABLED)); + SDL_Surface *surface=SDL_RenderReadPixels(renderer,NULL);CHECK(surface && surface->w==w && surface->h==h); + bool exact=w==1920 && h==1200; + if(exact) CHECK(rect.x==160 && rect.y==0 && rect.w==1600 && rect.h==1200); + for(int y=0;y=(int)ceil(rect.x+rect.w) || + y<(int)floor(rect.y) || y>=(int)ceil(rect.y+rect.h); + if(!border && !exact) continue; + Uint8 r,g,b,a;CHECK(SDL_ReadSurfacePixel(surface,x,y,&r,&g,&b,&a) && a==255); + if(border) CHECK(r==0 && g==0 && b==0); + else { + unsigned index=framebuffer[(y/6)*320+(x-160)/5];unsigned char colors[3]; + for(unsigned c=0;c<3;++c) { unsigned v=gamepal[index*3+c];colors[c]=(unsigned char)((v<<2)|(v>>4)); } + CHECK(r==colors[0] && g==colors[1] && b==colors[2]); + } + } + CHECK(SDL_SaveBMP(surface,path));SDL_DestroySurface(surface);CHECK(SDL_SetRenderLogicalPresentation(renderer,lw,lh,mode)); + printf("%s: %dx%d output, %.2fx%.2f centred DOS canvas; black borders verified%s\n", + name,w,h,(double)rect.w,(double)rect.h,exact?", every 5x6 source texel matches":""); +} +int main(int argc,char **argv) +{ + CHECK(argc==5);MM_Startup();CHECK(CA_Startup(argv[1]) && SD_Startup(48000) && VL_Startup() && VL_SetPalette(gamepal,768)); + int count;SDL_Window **windows=SDL_GetWindows(&count);CHECK(windows && count==1);window=windows[0];SDL_free(windows); + renderer=SDL_GetRenderer(window);CHECK(renderer);CHECK(SDL_AddEventWatch(Watch,NULL)); + DemoLoopStartupDevices(true,true,true); + CHECK(DemoLoopStartup(0,false) && DemoLoopIntro(0));ui_state next=DemoLoopState(); + CHECK(next==UI_TITLE || next==UI_RATING); + unsigned rng=US_RndIndex();uint32_t time=gamestate.TimeCount; + memcpy(before,framebuffer,sizeof(before));unsigned char saved_palette[768];memcpy(saved_palette,palette,768); + if(!strcmp(argv[4],"missing") || !strcmp(argv[4],"reject")) { + bool ok=DemoLoopSignon(argv[3],0); + if(!strcmp(argv[4],"missing")) CHECK(ok);else CHECK(!ok && strstr(CA_Error(),"Sign-on image")); + CHECK(DemoLoopState()==next && !memcmp(before,framebuffer,sizeof(before)) && !memcmp(saved_palette,palette,768)); + } else { + FILE *file=fopen(argv[3],"rb");CHECK(file && fread(raw,1,sizeof(raw),file)==sizeof(raw));CHECK(fclose(file)==0); + IN_KeyEvent(sc_Enter,true);CHECK(DemoLoopSignon(argv[3],0) && DemoLoopState()==UI_SIGNON && !IN_AnyPressed()); + Prompt("Press a key",14);CHECK(DemoLoop(10) && !memcmp(palette,gamepal,768)); + CHECK(DemoLoop(10000) && DemoLoopState()==UI_SIGNON);sd_status audio;SD_GetStatus(&audio);CHECK(audio.music==-1); + const int sizes[][2]={{640,480},{1920,1200},{1920,1080},{1280,800},{3440,1440},{3840,1080}}; + bool native=!strcmp(argv[4],"native"); + for(unsigned i=0;i<(native?1U:6U);++i) { + display_settings d=Settings();d.scale=0;d.width=native?1920:sizes[i][0];d.height=native?1200:sizes[i][1]; + d.fullscreen=native;d.integer=false;d.high_resolution=true;d.aspect=5;Set(d); + CHECK(!memcmp(palette,gamepal,768));Prompt("Press a key",14); + char name[32];CHECK(snprintf(name,sizeof(name),"signon-%u",i)>0);Capture(argv[2],name); + } + int width,height;CHECK(SDL_GetWindowSize(window,&width,&height));resizes=0; + Key(true,false);CHECK(DemoLoop(10001));Prompt("Working...",10);CHECK(!IN_AnyPressed()); + CHECK(DemoLoop(10011) && DemoLoopState()==next); + for(unsigned c=0;c<768;++c) CHECK(palette[c]==0); /* Fade out to black, not menu red. */ + Key(true,true);CHECK(DemoLoop(10041) && DemoLoopState()==next && !IN_AnyPressed());Key(false,false); + CHECK(!Keyboard[sc_Space] && !IN_NextASCII());SD_GetStatus(&audio);CHECK(audio.music==7); + int after_w,after_h;CHECK(SDL_GetWindowSize(window,&after_w,&after_h));CHECK(width==after_w && height==after_h && resizes==0); + if(next==UI_RATING) { + CHECK(DemoLoop(10530) && DemoLoopState()==UI_RATING); + CHECK(DemoLoop(10531) && DemoLoop(10561) && DemoLoopState()==UI_TITLE); + } + CHECK(US_RndIndex()==rng && gamestate.TimeCount==time && !GameRunning()); + /* Optional loader must not insert the historical page into menus. */ + CHECK(DemoLoopStartup(11000,true));memcpy(before,framebuffer,sizeof(before)); + CHECK(DemoLoopSignon(argv[3],11000) && DemoLoopState()==UI_MENU && !memcmp(before,framebuffer,sizeof(before))); + CHECK(DemoLoopStartGame(11000));memcpy(before,framebuffer,sizeof(before)); + CHECK(DemoLoopSignon(argv[3],11000) && DemoLoopState()==UI_GAME && !memcmp(before,framebuffer,sizeof(before)));GameStop(); + } + SDL_RemoveEventWatch(Watch,NULL);VL_Shutdown();SD_Shutdown();CA_Shutdown();MM_Shutdown();CHECK(!MM_TotalBytes()); + puts("Sign-on pixels, palette, prompt, startup order, input isolation and timing passed.");return 0; +} diff --git a/tests/synthetic_perf_benchmark.c b/tests/synthetic_perf_benchmark.c new file mode 100644 index 00000000..d3608649 --- /dev/null +++ b/tests/synthetic_perf_benchmark.c @@ -0,0 +1,200 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* R0.5 synthetic performance baseline: CPU renderer and optional SDL presentation. + Uses synthetic game fixtures only; no owned Wolfenstein data required. */ +#include "engine/WL_RENDER.h" +#include "engine/WL_SAVE.h" +#include "engine/WL_FRAME_CLOCK.h" +#include "engine/ID_CA.h" +#include "engine/ID_VL.h" +#include "engine/ID_SD.h" +#include "engine/WL_PROFILE.h" +#include "platform/sdl_video.h" +#include "platform/sdl_audio.h" +#include "engine/WL_CONTROLS.h" +#include "engine/WL_MAIN.h" +#include "engine/WL_DISPLAY.h" +#include +#include +#include +#include +#include +#include + +#define CHECK(x) do { if(!(x)) { fprintf(stderr,"CHECK failed: %s (%s:%d) CA=%s SDL=%s\n",#x,__FILE__,__LINE__,CA_Error(),SDL_GetError()); exit(1); } } while(0) + +#ifdef WOLF3D_BENCHMARK +wl_profile WL_Profile; +uint64_t WL_ProfileNow(void) { return SDL_GetTicksNS(); } +#endif + +static int cmp_u64(const void *a,const void *b) +{ + uint64_t x=*(const uint64_t*)a,y=*(const uint64_t*)b; return (x>y)-(xangle=180; actor->dir=west; actor->active=true; + doornum=1; tilemap[9][3]=128; doorobjlist[0]=(doorobj_t){9,3,0,true,dr_closed,0,0}; +} + +static void report_samples(const char *scene,const char *mode,unsigned w,unsigned h,unsigned n,uint64_t *samples) +{ + qsort(samples,n,sizeof(*samples),cmp_u64); + uint64_t sum=0; for(unsigned i=0;i [--sdl]\n",argv[0]); return 2; } + const char *data=argv[1], *user=argv[2]; + bool do_sdl=argc>3 && strcmp(argv[3],"--sdl")==0; + printf("CSV_HEADER,scene,mode,resolution,width,height,iterations,total_ns,min_ms,mean_ms,p50_ms,p95_ms,p99_ms,max_ms,rss_kb\n"); + printf("META,compiler,%s\n", +#ifdef __clang__ + "clang" +#elif defined(__GNUC__) + "gcc" +#else + "unknown" +#endif + ); + printf("META,compiler_version,%d.%d.%d\n", +#ifdef __GNUC__ + __GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__ +#else + 0,0,0 +#endif + ); +#ifdef __OPTIMIZE__ + printf("META,optimize,defined\n"); +#else + printf("META,optimize,not_defined\n"); +#endif + printf("META,data_dir,%s\n",data); + printf("META,rss_kb_start,%" PRIu64 "\n",rss_kb()); + MM_Startup(); CHECK(CA_Startup(data)); + bench_cpu("empty", setup_empty_scene); + bench_cpu("populated", setup_populated_scene); + if(do_sdl) bench_sdl(data,user); + CA_Shutdown(); MM_Shutdown(); + printf("META,rss_kb_end,%" PRIu64 "\n",rss_kb()); + printf("META,mm_total_bytes,%" PRIu64 "\n",(uint64_t)MM_TotalBytes()); + return 0; +} diff --git a/tests/test_audio.py b/tests/test_audio.py new file mode 100644 index 00000000..1e02c7c8 --- /dev/null +++ b/tests/test_audio.py @@ -0,0 +1,113 @@ +"""Original sound manager regressions, including a dummy SDL device.""" +import os +import re +from pathlib import Path +import shlex +import struct +import subprocess +import tempfile +import unittest +from test_engine import ROOT, fixtures +from audio_fixtures import audio_files + +class AudioTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + sdk = Path(os.environ.get('SDL_SDK', ROOT.parent / 'cart/vendor/SDL')) + library = sdk / 'build/libSDL3.a' + if not library.is_file(): + raise unittest.SkipTest('SDL_SDK must point to built static SDL3') + cls.temp = tempfile.TemporaryDirectory(prefix='w3r-audio-build-') + cls.addClassCleanup(cls.temp.cleanup) + cls.binary = Path(cls.temp.name) / 'audio-tests' + flags = ['-std=c11', '-Wall', '-Wextra', '-Wpedantic', '-Wconversion', '-Wshadow', '-Werror', '-g'] + if os.environ.get('SANITIZE') == '1': + flags += ['-fsanitize=address,undefined', '-fno-omit-frame-pointer'] + sources = sorted((ROOT / 'src/engine').glob('*.c')) + subprocess.run(shlex.split(os.environ.get('CC', 'gcc')) + flags + + ['-I' + str(ROOT / 'src'), '-I' + str(sdk / 'include'), str(ROOT / 'tests/audio_tests.c'), + *map(str, sources), str(ROOT / 'src/platform/data_file.c'), str(ROOT / 'src/platform/save_file.c'), str(ROOT / 'src/platform/sdl_audio.c'), + str(library), '-pthread', '-lm', '-o', str(cls.binary)], check=True) + + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix='w3r-audio-data-') + self.addCleanup(self.temp.cleanup) + self.data = Path(self.temp.name) + fixtures(self.data, ui=True) + audio_files(self.data) + + def run_audio(self, path=None, *args): + return subprocess.run([str(self.binary), str(path or self.data), *args], check=True, + env=dict(os.environ, SDL_AUDIODRIVER='dummy')) + + def test_original_metadata(self): + original = (ROOT / 'WOLFSRC/WL_MAIN.C').read_text(encoding='latin1') + table = original.split('static int wolfdigimap[]')[1].split('#else')[0] + expected = {name: int(index) + 1 for name, index in + re.findall(r'([A-Z0-9_]+SND),\s*(\d+)', table)} + port = (ROOT / 'src/engine/ID_SD.c').read_text() + actual = {name: int(index) for name, index in + re.findall(r'\[([A-Z0-9_]+SND)\]\s*=\s*(\d+)', port)} + self.assertEqual(actual, expected) + songs = (ROOT / 'WOLFSRC/WL_PLAY.C').read_text(encoding='latin1') + music_names = re.findall(r'([A-Z0-9_]+_MUS),?', songs.split('int songs[]=')[1].split('#else')[0]) + header = (ROOT / 'WOLFSRC/AUDIOWL6.H').read_text() + ids = dict((name, int(index)) for name, index in re.findall(r'([A-Z0-9_]+_MUS),\s*//\s*(\d+)', header)) + expected = [ids[name] for name in music_names] + values = port.split('static const int songs[60]={')[1].split('}')[0] + self.assertEqual(list(map(int, re.findall(r'\d+', values))), expected) + + def test_synthetic_audio(self): + self.run_audio() + + def test_gameplay_audio_independence(self): + from game_fixtures import finale_files + finale_files(self.data) + audio_files(self.data) + self.run_audio(None, 'gameplay') + + def test_readonly_audio_data(self): + files = list(self.data.iterdir()) + try: + for file in files: + file.chmod(0o444) + self.data.chmod(0o555) + self.run_audio() + finally: + self.data.chmod(0o755) + for file in files: + file.chmod(0o644) + + def test_owned_audio(self): + if not os.environ.get('WOLF3D_DATA'): + self.skipTest('Set WOLF3D_DATA to owned WL6 files') + self.run_audio(os.environ['WOLF3D_DATA'], 'owned') + + def test_corrupt_audio(self): + for name in ['AUDIOHED.WL6', 'AUDIOT.WL6', 'VSWAP.WL6']: + file = self.data / name + original = file.read_bytes() + for length in [0, 1, 5, len(original) - 1]: + with self.subTest(name=name, length=length): + file.write_bytes(original[:length]) + self.run_audio(None, 'invalid') + file.write_bytes(original) + head = self.data / 'AUDIOHED.WL6' + original = head.read_bytes() + for index in [0, 87, 174, 261, 288]: + with self.subTest(offset=index): + raw = bytearray(original) + struct.pack_into(' 1: + parent = [] + for i in range(0, len(level), 2): + parent.append(256 + len(nodes)) + nodes.append((level[i], level[i + 1])) + level = parent + return b"".join(struct.pack("> bit) & 1] + if code >= 256: node = code - 256 + else: + planar.append(code); node = 254 + if len(planar) == 64000: break + if len(planar) == 64000: break + self.assertEqual(len(planar), 64000) + pixels = bytearray(64000) + for plane in range(4): pixels[plane::4] = planar[plane * 16000:(plane + 1) * 16000] + self.compare_assets(directory, pixels) + subprocess.run([str(self.output / "ui-tests"),str(directory),"owned"],check=True) + dump=self.data/"owned-map-texture.bin" + subprocess.run([str(self.output / "game-tests"),str(directory),"owned",str(dump)],check=True) + subprocess.run([str(self.output / "campaign-tests"),str(directory),"owned"],check=True) + subprocess.run([str(self.output / "combat-tests"),str(directory),"owned"],check=True) + from game_fixtures import original_map_oracle + self.assertEqual(dump.read_bytes(),original_map_oracle(directory)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_git_protection.py b/tests/test_git_protection.py new file mode 100644 index 00000000..977d1f03 --- /dev/null +++ b/tests/test_git_protection.py @@ -0,0 +1,59 @@ +"""Exercise the pre-push hook directly; never invoke git push or a network operation.""" +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +HOOK = ROOT / ".githooks" / "pre-push" + + +class PushProtection(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.cwd = self.temp.name + self.env = dict(os.environ, GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull) + subprocess.run(["git", "init", "-q", self.cwd], check=True, env=self.env) + + def git(self, *args): + subprocess.run(["git", *args], cwd=self.cwd, env=self.env, check=True) + + def hook(self, remote, url): + return subprocess.run([str(HOOK), remote, url], cwd=self.cwd, env=self.env, + input="", text=True, capture_output=True) + + def test_original_urls_rejected(self): + for url in ( + "https://github.com/id-Software/wolf3d.git", + "git@github.com:id-Software/wolf3d.git", + "ssh://git@github.com/id-Software/wolf3d.git", + "https://github.com/ID-SOFTWARE/WOLF3D", + "git://github.com/id-Software/wolf3d", + ): + with self.subTest(url=url): + self.assertNotEqual(self.hook("arbitrary", url).returncode, 0) + + def test_owned_origin_allowed(self): + url = "https://github.com/raygibbon/wolf3d-revive.git" + self.git("remote", "add", "origin", url) + self.assertEqual(self.hook("origin", url).returncode, 0) + + def test_all_configured_push_urls_checked(self): + url = "https://github.com/raygibbon/wolf3d-revive.git" + self.git("remote", "add", "alias", url) + self.git("remote", "set-url", "--add", "--push", "alias", url) + self.git("remote", "set-url", "--add", "--push", "alias", + "git@github.com:id-Software/wolf3d.git") + self.assertNotEqual(self.hook("alias", url).returncode, 0) + + def test_url_rewrite_checked(self): + self.git("remote", "add", "alias", "wolf-original:repo") + self.git("config", "url.https://github.com/id-Software/wolf3d.pushInsteadOf", + "wolf-original:") + self.assertNotEqual(self.hook("alias", "wolf-original:repo").returncode, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_loading.py b/tests/test_loading.py new file mode 100644 index 00000000..18870b8a --- /dev/null +++ b/tests/test_loading.py @@ -0,0 +1,44 @@ +"""DOS PreloadGraphics and Died presentation, synthetic and privately owned data.""" +import os +from pathlib import Path +import shlex +import subprocess +import tempfile +import unittest +from test_engine import ROOT +from game_fixtures import finale_files + + +class LoadingTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + sdk = Path(os.environ.get('SDL_SDK', ROOT.parent / 'cart/vendor/SDL')) + if not (sdk / 'build/libSDL3.a').is_file(): + raise unittest.SkipTest('SDL SDK unavailable') + cls.build = tempfile.TemporaryDirectory(prefix='w3r-loading-') + cls.addClassCleanup(cls.build.cleanup) + cls.binary = Path(cls.build.name) / 'loading-tests' + flags = ['-std=c11', '-Wall', '-Wextra', '-Wpedantic', '-Wconversion', '-Wshadow', '-Werror', '-g'] + if os.environ.get('SANITIZE') == '1': + flags += ['-fsanitize=address,undefined', '-fno-omit-frame-pointer'] + sources = sorted(p for p in (ROOT / 'src').rglob('*.c') if p.name != 'main.c') + subprocess.run(shlex.split(os.environ.get('CC', 'gcc')) + flags + + ['-I' + str(ROOT / 'src'), '-I' + str(sdk / 'include'), str(ROOT / 'tests/loading_tests.c'), + *map(str, sources), str(sdk / 'build/libSDL3.a'), '-pthread', '-lm', '-o', str(cls.binary)], check=True) + + def run_case(self, data, mode): + with tempfile.TemporaryDirectory(prefix='w3r-loading-saves-') as saves: + env = dict(os.environ, SDL_VIDEODRIVER='dummy', SDL_RENDER_DRIVER='software', SDL_AUDIODRIVER='dummy') + subprocess.run([str(self.binary), str(data), saves, mode], env=env, check=True, timeout=180) + + def test_synthetic_loading_and_death(self): + with tempfile.TemporaryDirectory(prefix='w3r-loading-data-') as directory: + data = Path(directory) + finale_files(data) + self.run_case(data, 'synthetic') + + def test_owned_loading_and_death(self): + data = os.environ.get('WOLF3D_DATA') + if not data: + self.skipTest('Set WOLF3D_DATA to legally owned WL6 data') + self.run_case(data, 'owned') diff --git a/tests/test_presentation.py b/tests/test_presentation.py new file mode 100644 index 00000000..785376f8 --- /dev/null +++ b/tests/test_presentation.py @@ -0,0 +1,35 @@ +"""Immutable interpolation, independent render rates and exact simulation state.""" +import os +from pathlib import Path +import shlex +import subprocess +import tempfile +import unittest +from test_engine import ROOT +from game_fixtures import finale_files + +class PresentationTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.build=tempfile.TemporaryDirectory(prefix='w3r-present-');cls.addClassCleanup(cls.build.cleanup) + sdk=Path(os.environ.get('SDL_SDK',ROOT.parent/'cart/vendor/SDL')) + cls.cc=shlex.split(os.environ.get('CC','gcc')) + cls.flags=['-std=c11','-Wall','-Wextra','-Wpedantic','-Wconversion','-Wshadow','-Werror','-g'] + if os.environ.get('SANITIZE')=='1': cls.flags+=['-fsanitize=address,undefined','-fno-omit-frame-pointer'] + cls.clock=Path(cls.build.name)/'clock';cls.binary=Path(cls.build.name)/'presentation' + subprocess.run(cls.cc+cls.flags+['-I'+str(ROOT/'src'),str(ROOT/'tests/frame_clock_tests.c'),str(ROOT/'src/engine/WL_FRAME_CLOCK.c'),'-o',str(cls.clock)],check=True) + sources=sorted(p for p in (ROOT/'src').rglob('*.c') if p.name!='main.c') + subprocess.run(cls.cc+cls.flags+['-I'+str(ROOT/'src'),'-I'+str(sdk/'include'),str(ROOT/'tests/presentation_tests.c'),*map(str,sources),str(sdk/'build/libSDL3.a'),'-pthread','-lm','-o',str(cls.binary)],check=True) + def test_clock(self): subprocess.run([str(self.clock)],check=True) + def run_world(self,owned): + with tempfile.TemporaryDirectory(prefix='w3r-present-data-') as directory: + root=Path(directory);data=root/'data';data.mkdir() + if owned: + if not os.environ.get('WOLF3D_DATA'): self.skipTest('Owned WL6 data unavailable') + data=Path(os.environ['WOLF3D_DATA']) + else: finale_files(data) + subprocess.run([str(self.binary),str(data),str(root)],check=True) + payloads=[(root/f'slot{i+1}.w3s').read_bytes()[96:] for i in range(5)] + for payload in payloads[1:]: self.assertEqual(payload,payloads[0]) + def test_synthetic(self): self.run_world(False) + def test_owned(self): self.run_world(True) diff --git a/tests/test_render.py b/tests/test_render.py new file mode 100644 index 00000000..6b36837e --- /dev/null +++ b/tests/test_render.py @@ -0,0 +1,162 @@ +"""Resolution-independent indexed rendering, SDL composition and isolation.""" +import os +import hashlib +import json +from pathlib import Path +import shlex +import subprocess +import tempfile +import unittest +import zipfile +from test_engine import ROOT +from game_fixtures import finale_files +from visual_baseline import (IndexedCapture, capture_manifest, compare_metadata, + compare_pixels, create_review_bmps, validate_manifest, + require_exact_pixels, write_baseline_archive, write_manifest) + +BASELINE_MANIFEST = ROOT/'tests/fixtures/visual_baselines.json' +BASELINE_ARCHIVE = ROOT/'tests/fixtures/visual_baselines.zip' + + +def _rebuild_archive(source: Path, destination: Path, *, omit: set[str] | None = None, + corrupt: set[str] | None = None) -> None: + """Copy a baseline archive, omitting IDs or mutating one pixel per corrupt ID.""" + omit = omit or set() + corrupt = corrupt or set() + with zipfile.ZipFile(source) as original, zipfile.ZipFile(destination, "w") as rebuilt: + for info in original.infolist(): + capture_id = info.filename[:-4] if info.filename.endswith(".w3i") else info.filename + if capture_id in omit: + continue + data = original.read(info.filename) + if capture_id in corrupt: + data = data[:16] + bytes([data[16] ^ 1]) + data[17:] + rebuilt.writestr(info, data) + + +class RenderTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.build = tempfile.TemporaryDirectory(prefix='w3r-render-build-') + cls.addClassCleanup(cls.build.cleanup) + cls.flags = ['-std=c11','-Wall','-Wextra','-Wpedantic','-Wconversion','-Wshadow','-Werror','-g'] + if os.environ.get('SANITIZE') == '1': cls.flags += ['-fsanitize=address,undefined','-fno-omit-frame-pointer'] + cls.cc = shlex.split(os.environ.get('CC','gcc')) + cls.target = Path(cls.build.name)/'target' + subprocess.run(cls.cc+cls.flags+['-I'+str(ROOT/'src'),str(ROOT/'tests/render_target_tests.c'),str(ROOT/'src/engine/WL_RENDER_TARGET.c'),'-o',str(cls.target)],check=True) + sdk = Path(os.environ.get('SDL_SDK',ROOT.parent/'cart/vendor/SDL')) + cls.binary = Path(cls.build.name)/'render' + sources = sorted(p for p in (ROOT/'src').rglob('*.c') if p.name!='main.c') + subprocess.run(cls.cc+cls.flags+['-DWOLF3D_DISPLAY_TEST','-I'+str(ROOT/'src'),'-I'+str(sdk/'include'),str(ROOT/'tests/render_tests.c'),*map(str,sources),str(sdk/'build/libSDL3.a'),'-pthread','-lm','-o',str(cls.binary)],check=True) + + def test_original_framebuffer_hashes(self): + if not os.environ.get('WOLF3D_DATA'): self.skipTest('Owned data unavailable') + data=Path(os.environ['WOLF3D_DATA']) + identities=json.loads((ROOT/'tests/fixtures/dos_demo_hashes.json').read_text())['assets'] + files={p.name.upper():p for p in data.iterdir()} + for name,identity in identities.items(): + if name not in files or hashlib.sha256(files[name].read_bytes()).hexdigest()!=identity: + self.skipTest('Different original data revision') + binary=Path(self.build.name)/'original' + sources=sorted((ROOT/'src/engine').glob('*.c')) + subprocess.run(self.cc+self.flags+['-I'+str(ROOT/'src'),str(ROOT/'tests/render_original_tests.c'),*map(str,sources),str(ROOT/'src/platform/data_file.c'),str(ROOT/'src/platform/save_file.c'),'-lm','-o',str(binary)],check=True) + output=subprocess.check_output([str(binary),str(data)],text=True) + self.assertEqual(output,(ROOT/'tests/fixtures/original_render_hashes.csv').read_text()) + + def test_native_framebuffer_hashes(self): + if not os.environ.get('WOLF3D_DATA'): self.skipTest('Owned data unavailable') + data=Path(os.environ['WOLF3D_DATA']) + identities=json.loads((ROOT/'tests/fixtures/dos_demo_hashes.json').read_text())['assets'] + files={p.name.upper():p for p in data.iterdir()} + for name,identity in identities.items(): + if name not in files or hashlib.sha256(files[name].read_bytes()).hexdigest()!=identity: + self.skipTest('Different original data revision') + binary=Path(self.build.name)/'native' + sources=sorted((ROOT/'src/engine').glob('*.c')) + subprocess.run(self.cc+self.flags+['-I'+str(ROOT/'src'),str(ROOT/'tests/render_native_hashes.c'),*map(str,sources),str(ROOT/'src/platform/data_file.c'),str(ROOT/'src/platform/save_file.c'),'-lm','-o',str(binary)],check=True) + output=subprocess.check_output([str(binary),str(data)],text=True) + self.assertEqual(output,(ROOT/'tests/fixtures/native_render_hashes.csv').read_text()) + + def test_aspect(self): + binary=Path(self.build.name)/'aspect' + subprocess.run(self.cc+self.flags+['-I'+str(ROOT/'src'),str(ROOT/'tests/aspect_tests.c'),str(ROOT/'src/engine/WL_ASPECT.c'),'-lm','-o',str(binary)],check=True) + subprocess.run([str(binary)],check=True) + + def test_target(self): subprocess.run([str(self.target)],check=True) + def run_render(self,owned=False): + with tempfile.TemporaryDirectory(prefix='w3r-render-data-') as directory: + root=Path(directory);data=root/'data';data.mkdir() + if owned: + if not os.environ.get('WOLF3D_DATA'): self.skipTest('Owned data unavailable') + data=Path(os.environ['WOLF3D_DATA']) + else: finale_files(data) + env=dict(os.environ,SDL_VIDEODRIVER='dummy',SDL_RENDER_DRIVER='software',SDL_AUDIODRIVER='dummy',XDG_DATA_HOME=str(root)) + captures = None + if not owned: + configured = os.environ.get('WOLF3D_BASELINE_DIR') + captures = Path(configured) if configured else root/'visual-baseline' + captures.mkdir(parents=True, exist_ok=True) + env['WOLF3D_BASELINE_DIR'] = str(captures) + subprocess.run([str(self.binary),str(data),str(root),"owned" if owned else "synthetic"],env=env,check=True) + shots=list((root/'wolf3d-revive').glob('screenshot-*.bmp')) + self.assertEqual(len(shots),2) + for shot in shots: self.assertEqual(shot.read_bytes()[:2],b'BM') + self.assertEqual((root/"slot1.w3s").read_bytes()[96:],(root/"slot2.w3s").read_bytes()[96:]) + if captures: + manifest = capture_manifest(captures, data) + if os.environ.get('WOLF3D_UPDATE_BASELINES') == '1': + write_manifest(BASELINE_MANIFEST, manifest) + write_baseline_archive(BASELINE_ARCHIVE, captures) + validate_manifest(manifest, BASELINE_MANIFEST, captures, BASELINE_ARCHIVE) + initial = next(x for x in manifest['captures'] if x['id']=='display-transition-classic-initial-640x480') + restored = next(x for x in manifest['captures'] if x['id']=='display-transition-classic-restored-640x480') + self.assertEqual(initial['pixel_hash'], restored['pixel_hash']) + initial = next(x for x in manifest['captures'] if x['id']=='display-transition-enhanced-initial-640x480-4x3') + restored = next(x for x in manifest['captures'] if x['id']=='display-transition-enhanced-restored-640x480-4x3') + self.assertEqual(initial['pixel_hash'], restored['pixel_hash']) + write_manifest(captures/'manifest.json', manifest) + if configured: create_review_bmps(captures) + def test_render_and_settings(self): self.run_render() + def test_owned_render(self): self.run_render(True) + + def test_visual_comparator_failures(self): + original = IndexedCapture(3, 2, bytes((1, 2, 3, 4, 5, 6))) + self.assertEqual(compare_pixels(original, original).changed_pixels, 0) + changed = IndexedCapture(3, 2, bytes((1, 2, 3, 4, 9, 6))) + difference = compare_pixels(original, changed) + self.assertEqual(difference.changed_pixels, 1) + self.assertEqual(difference.bounding_box, (1, 1, 1, 1)) + with self.assertRaisesRegex(ValueError, 'changed_pixels=1.*bounding_box=\\(1, 1, 1, 1\\)'): + require_exact_pixels(original, changed, 'single-pixel mutation') + with self.assertRaisesRegex(ValueError, 'dimension mismatch'): + compare_pixels(original, IndexedCapture(2, 3, original.pixels)) + with self.assertRaisesRegex(ValueError, 'metadata mismatch'): + compare_metadata({'scene_id':'corridor-static'}, {'scene_id':'door-motion'}) + + def test_validate_manifest_rejects_missing_archive_entry(self): + """A matching candidate must not hide a missing archived baseline.""" + manifest = json.loads(BASELINE_MANIFEST.read_text(encoding='utf-8')) + missing_id = manifest['captures'][0]['id'] + with tempfile.TemporaryDirectory(prefix='w3r-baseline-missing-') as directory: + root = Path(directory) + captures = root/'captures' + with zipfile.ZipFile(BASELINE_ARCHIVE) as archive: + archive.extractall(captures) + broken = root/'baseline.zip' + _rebuild_archive(BASELINE_ARCHIVE, broken, omit={missing_id}) + with self.assertRaisesRegex(ValueError, 'capture ID set'): + validate_manifest(manifest, BASELINE_MANIFEST, captures, broken) + + def test_validate_manifest_rejects_corrupted_archived_pixels(self): + """Every archived pixel payload is verified even when hashes agree.""" + manifest = json.loads(BASELINE_MANIFEST.read_text(encoding='utf-8')) + corrupted_id = manifest['captures'][0]['id'] + with tempfile.TemporaryDirectory(prefix='w3r-baseline-corrupt-') as directory: + root = Path(directory) + captures = root/'captures' + with zipfile.ZipFile(BASELINE_ARCHIVE) as archive: + archive.extractall(captures) + broken = root/'baseline.zip' + _rebuild_archive(BASELINE_ARCHIVE, broken, corrupt={corrupted_id}) + with self.assertRaisesRegex(ValueError, 'archived baseline hash mismatch'): + validate_manifest(manifest, BASELINE_MANIFEST, captures, broken) diff --git a/tests/test_save.py b/tests/test_save.py new file mode 100644 index 00000000..7084b8ce --- /dev/null +++ b/tests/test_save.py @@ -0,0 +1,187 @@ +"""Portable saves: integrity, transactional loads, deterministic continuation.""" +import os +from pathlib import Path +import shlex +import struct +import subprocess +import tempfile +import unittest +import zlib +from test_engine import ROOT, fixtures +from game_fixtures import finale_files + +class SaveTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.temp = tempfile.TemporaryDirectory(prefix='w3r-save-build-') + cls.addClassCleanup(cls.temp.cleanup) + cls.binary = Path(cls.temp.name) / 'save-tests' + flags = ['-std=c11', '-Wall', '-Wextra', '-Wpedantic', '-Wconversion', '-Wshadow', '-Werror', '-g'] + if os.environ.get('SANITIZE') == '1': + flags += ['-fsanitize=address,undefined', '-fno-omit-frame-pointer'] + subprocess.run(shlex.split(os.environ.get('CC', 'gcc')) + flags + ['-I' + str(ROOT / 'src'), + str(ROOT / 'tests/save_tests.c'), *map(str, sorted((ROOT / 'src/engine').glob('*.c'))), + str(ROOT / 'src/platform/data_file.c'), str(ROOT / 'src/platform/save_file.c'), + '-lm', '-o', str(cls.binary)], check=True) + + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix='w3r-save-data-') + self.addCleanup(self.temp.cleanup) + self.data = Path(self.temp.name) / 'data' + self.slots = Path(self.temp.name) / 'saves' + self.data.mkdir(); self.slots.mkdir() + fixtures(self.data, ui=True); finale_files(self.data) + + def run_save(self, *args, **kwargs): + return subprocess.run([str(self.binary), str(self.data), str(self.slots), *args], check=True, **kwargs) + + def payload(self, slot): + return (self.slots / f'slot{slot}.w3s').read_bytes()[96:] + + def seed(self): + self.run_save() + + def reject(self, raw, checksum=True): + raw = bytearray(raw) + if checksum: + struct.pack_into('> 5) | (length-2 if 3 <= length <= 9 else 0))) + if not 3 <= length <= 9: self.data.append(length-1) + def end(self): + self.long(-8192, 1) # Extended length 0 is the end marker. + return bytes(self.data) + + +class ExtractionTests(unittest.TestCase): + def test_literals_and_control_prefetch(self): + packed = Packed(); expected = bytes(range(256))*2 + for value in expected: packed.literal(value) + self.assertEqual(extractor.decode_stream(packed.end(), 0, len(expected)), expected) + def test_overlapping_short_and_long_references(self): + packed = Packed(); packed.literal(65); packed.short(-1, 5); packed.long(-1, 100) + packed.long(-8192, 2) # Extended length 1 is a segment marker. + packed.literal(66); packed.long(-2, 9) + self.assertEqual(extractor.decode_stream(packed.end(), 0, 116), b'A'*106 + b'BA'*5) + def test_stream_bounds_and_invalid_references(self): + packed = Packed(); packed.literal(42); data = packed.end() + for length in range(len(data)): + with self.subTest(length=length), self.assertRaises(ValueError): extractor.decode_stream(data[:length], 0, 1) + packed = Packed(); packed.short(-1, 2) + with self.assertRaisesRegex(ValueError, 'backreference'): extractor.decode_stream(packed.end(), 0, 100) + packed = Packed(); packed.literal(1); packed.literal(2) + with self.assertRaisesRegex(ValueError, 'exceeds'): extractor.decode_stream(packed.end(), 0, 1) + with self.assertRaisesRegex(ValueError, 'Truncated'): extractor.decode_stream(b'', -1, 100) + def test_unknown_executable_is_rejected(self): + for data in (b'', b'MZ'+bytes(100), bytes(108779)): + with self.assertRaisesRegex(ValueError, 'Unsupported'): extractor.extract(data) + def test_output_locations_and_input_bounds(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory); source = root/'input.exe'; source.write_bytes(bytes(1024*1024+1)) + with self.assertRaisesRegex(ValueError, 'separate'): extractor.export(source, source) + with self.assertRaisesRegex(ValueError, 'outside'): extractor.export(source, ROOT/'SIGNON.RAW') + with self.assertRaisesRegex(ValueError, 'exceeds'): extractor.export(source, root/'SIGNON.RAW') + self.assertFalse((root/'SIGNON.RAW').exists()) + def test_source_object_and_directory_extraction(self): + source = ROOT/'WOLFSRC/OBJ/SIGNON.OBJ' + pixels = extractor.extract(source.read_bytes()) + self.assertEqual(len(pixels), 64000) + self.assertEqual(hashlib.sha256(pixels).hexdigest(), extractor.SOURCE_SIGNON_SHA256) + with tempfile.TemporaryDirectory() as directory: + for number,path in enumerate((source, ROOT/'WOLFSRC', ROOT)): + output = Path(directory)/f'{number}.raw' + self.assertEqual(extractor.export(path, output), extractor.SOURCE_SIGNON_SHA256) + self.assertEqual(output.read_bytes(), pixels) + def test_object_bounds_checksums_and_coverage(self): + def record(kind, payload): + data = bytes([kind]) + struct.pack('> 4) for v in original_palette()) + for y in range(189): + for x in range(320): + px,py = x*3+1, int((y+0.5)*3.6) + row = py if height < 0 else height-1-py + at = offset+row*stride+px*pixel_bytes; index = self.pixels[y*320+x]; r,g,b = palette[index*3:index*3+3] + self.assertEqual(bmp[at:at+3], bytes((b,g,r)), (x,y)) diff --git a/tests/test_transition_audit.py b/tests/test_transition_audit.py new file mode 100644 index 00000000..78347f3a --- /dev/null +++ b/tests/test_transition_audit.py @@ -0,0 +1,86 @@ +"""Guard the checked-in DOS inventory and fail closed on missing/stale evidence.""" +import copy +import importlib.util +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location('transition_audit', ROOT/'scripts/audit_transitions.py') +audit = importlib.util.module_from_spec(spec) +spec.loader.exec_module(audit) + + +class TransitionAuditTests(unittest.TestCase): + def setUp(self): + self.data = json.loads(audit.MANIFEST.read_text()) + + def test_checked_in_inventory_and_document(self): + audit.validate(self.data) + self.assertEqual(audit.DOCUMENT.read_text(), audit.render(self.data)) + + def test_missing_invalid_and_stale_inventory_files(self): + with tempfile.TemporaryDirectory() as directory: + manifest = Path(directory)/'inventory.json' + document = Path(directory)/'inventory.md' + with patch.object(audit, 'MANIFEST', manifest), patch.object(audit, 'DOCUMENT', document), patch.object(sys, 'argv', ['audit', '--check']): + with self.assertRaises(SystemExit) as missing_manifest: + audit.main() + self.assertEqual(missing_manifest.exception.code, 1) + manifest.write_text('{bad json') + with self.assertRaises(SystemExit): + audit.main() + manifest.write_text(json.dumps(self.data)) + with self.assertRaises(SystemExit): + audit.main() + document.write_text('stale') + with self.assertRaises(SystemExit): + audit.main() + with patch.object(sys, 'argv', ['audit', '--write']): + audit.main() + audit.main() + + def test_rejects_semantic_and_reference_corruption(self): + def mutate(field, value): + data = copy.deepcopy(self.data) + data['transitions'][0][field] = value + return data + cases = [mutate('palette', ''), mutate('evidence', []), + mutate('implementation', []), mutate('source', ['unknown']), + mutate('from', 'unmapped'), mutate('status', 'pixel-perfect'), + mutate('gaps', [])] + data = copy.deepcopy(self.data) + data['transitions'] = [t for t in data['transitions'] if t['id'] != 'psyched-progress'] + cases.append(data) + for key, value in [('native_ui', {}), ('dos_exits', {}), ('original_sha256', {}), + ('journeys', {'bad': ['startup', 'quick-resume']})]: + data = copy.deepcopy(self.data) + data[key] = value + cases.append(data) + data = copy.deepcopy(self.data) + next(iter(data['references'].values()))['anchor'] = 'missing original function' + cases.append(data) + data = copy.deepcopy(self.data) + next(iter(data['references'].values()))['path'] = '../outside' + cases.append(data) + data = copy.deepcopy(self.data) + key = next(iter(data['original_sha256'])) + data['original_sha256'][key] = '0'*64 + cases.append(data) + data = copy.deepcopy(self.data) + data['transitions'].append(data['transitions'][0]) + cases.append(data) + for index, data in enumerate(cases): + with self.subTest(case=index), self.assertRaises(ValueError): + audit.validate(data) + + def test_checks_survive_python_optimization(self): + # Python -O removed the previous assert-based validation entirely. + program = "import runpy; a=runpy.run_path('scripts/audit_transitions.py'); a['validate']({'schema': 999})" + result = subprocess.run([sys.executable, '-O', '-c', program], cwd=ROOT, capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn('ValueError', result.stderr) diff --git a/tests/test_validation_runner.py b/tests/test_validation_runner.py new file mode 100644 index 00000000..69073a5e --- /dev/null +++ b/tests/test_validation_runner.py @@ -0,0 +1,281 @@ +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +RUNNER_PATH = ROOT / "tools" / "validation" / "run.py" + + +def load_runner(): + spec = importlib.util.spec_from_file_location("w3r_validation_run", RUNNER_PATH) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + sys.modules[spec.name] = mod + spec.loader.exec_module(mod) + return mod + + +class ValidationRunnerTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.runner = load_runner() + + def make_job(self, **kw): + defaults = dict( + id="j1", + milestone="R0.6", + milestones=("R0.6", "all"), + description="test job", + command=[sys.executable, "-c", "print('ok')"], + timeout=30, + mandatory=True, + category="meta", + ) + defaults.update(kw) + return self.runner.Job(**defaults) + + def assert_process_finished(self, pid, message): + for _ in range(50): + info = self.runner._process_info(pid) + if info is None or info[0] == "Z": + return + time.sleep(0.02) + self.fail(f"{message}: process {pid} remains active") + + def test_successful_job_produces_pass(self): + with tempfile.TemporaryDirectory() as td: + run_dir = Path(td) + job = self.make_job(command=[sys.executable, "-c", "print('hello')"]) + r = self.runner.run_job(job, run_dir) + self.assertEqual(r.status, "PASS") + self.assertEqual(r.exit_code, 0) + self.assertTrue((run_dir / "j1.log").exists()) + self.assertIn("hello", (run_dir / "j1.log").read_text()) + + def test_parent_and_child_exit_normally_produces_pass(self): + with tempfile.TemporaryDirectory() as td: + run_dir = Path(td) + cmd = [sys.executable, "-c", + "import subprocess,sys;" + "subprocess.run([sys.executable,'-c','print(42)'],check=True)"] + r = self.runner.run_job(self.make_job(command=cmd), run_dir) + self.assertEqual((r.status, r.exit_code), ("PASS", 0)) + + def test_nonzero_exit_produces_fail(self): + with tempfile.TemporaryDirectory() as td: + run_dir = Path(td) + job = self.make_job(command=[sys.executable, "-c", "import sys; sys.exit(7)"]) + r = self.runner.run_job(job, run_dir) + self.assertEqual(r.status, "FAIL") + self.assertEqual(r.exit_code, 7) + + def test_timeout_produces_timeout_and_kills_child(self): + with tempfile.TemporaryDirectory() as td: + run_dir = Path(td) + pidfile = run_dir / "child.pid" + cmd = [sys.executable, "-c", + "import os,time,subprocess,sys;" + f"p=subprocess.Popen([sys.executable,'-c','import time; time.sleep(60)']);" + f"open(r'{pidfile}','w').write(str(p.pid));" + "time.sleep(60)"] + job = self.make_job(command=cmd, timeout=2) + start = time.time() + r = self.runner.run_job(job, run_dir) + elapsed = time.time() - start + self.assertEqual(r.status, "TIMEOUT") + self.assertLess(elapsed, 15) + # child process should be dead + if pidfile.exists(): + child_pid = int(pidfile.read_text().strip()) + # wait a moment for cleanup + for _ in range(20): + try: + os.kill(child_pid, 0) + except ProcessLookupError: + break + time.sleep(0.1) + else: + self.fail(f"child process {child_pid} still alive after timeout") + + def test_missing_prereq_mandatory_is_not_run(self): + with tempfile.TemporaryDirectory() as td: + run_dir = Path(td) + job = self.make_job(requires=("sdl-sdk",), mandatory=True) + # Force missing prereq by pointing SDL_SDK to nonexistent + old = os.environ.get("SDL_SDK") + os.environ["SDL_SDK"] = "/tmp/definitely-missing-sdl-sdk" + try: + r = self.runner.run_job(job, run_dir) + finally: + if old is None: + os.environ.pop("SDL_SDK", None) + else: + os.environ["SDL_SDK"] = old + self.assertEqual(r.status, "NOT RUN") + self.assertIsNone(r.exit_code) + + def test_missing_prereq_optional_is_skip(self): + with tempfile.TemporaryDirectory() as td: + run_dir = Path(td) + job = self.make_job(requires=("sdl-sdk",), mandatory=False) + old = os.environ.get("SDL_SDK") + os.environ["SDL_SDK"] = "/tmp/definitely-missing-sdl-sdk" + try: + r = self.runner.run_job(job, run_dir) + finally: + if old is None: + os.environ.pop("SDL_SDK", None) + else: + os.environ["SDL_SDK"] = old + self.assertIn(r.status, ("SKIP", "NOT RUN")) + + def test_json_summary_matches_execution(self): + with tempfile.TemporaryDirectory() as td: + run_dir = Path(td) / "R0.6" / "testrun" + run_dir.mkdir(parents=True) + j1 = self.make_job(id="pass-job", command=[sys.executable, "-c", "pass"]) + j2 = self.make_job(id="fail-job", command=[sys.executable, "-c", "import sys; sys.exit(2)"]) + started = self.runner._utcnow() + r1 = self.runner.run_job(j1, run_dir) + r2 = self.runner.run_job(j2, run_dir) + ended = self.runner._utcnow() + sp = self.runner.write_summary(run_dir, "R0.6", [r1, r2], started, ended) + data = json.loads(sp.read_text()) + self.assertEqual(data["overall_status"], "FAIL") + self.assertEqual(len(data["jobs"]), 2) + ids = [j["id"] for j in data["jobs"]] + self.assertEqual(ids, ["pass-job", "fail-job"]) + self.assertEqual(data["jobs"][0]["status"], "PASS") + self.assertEqual(data["jobs"][1]["status"], "FAIL") + + def test_required_job_failure_causes_nonzero_overall(self): + r1 = self.runner.JobResult("a","R0.6","d",["x"],"meta",True,10,"PASS",0,1.0,"","","l") + r2 = self.runner.JobResult("b","R0.6","d",["x"],"meta",True,10,"FAIL",1,1.0,"","","l") + self.assertEqual(self.runner.overall_status([r1,r2]), "FAIL") + + def test_optional_skip_does_not_fail_overall(self): + r1 = self.runner.JobResult("a","R0.6","d",["x"],"meta",True,10,"PASS",0,1.0,"","","l") + r2 = self.runner.JobResult("b","R0.6","d",["x"],"meta",False,10,"SKIP",None,0.0,"","","l","missing") + self.assertEqual(self.runner.overall_status([r1,r2]), "PASS") + + def test_unknown_milestone_rejected(self): + proc = subprocess.run([sys.executable, str(RUNNER_PATH), "R9.9"], capture_output=True, text=True) + self.assertNotEqual(proc.returncode, 0) + self.assertIn("unknown milestone", proc.stderr + proc.stdout) + + def test_invalid_args_rejected(self): + proc = subprocess.run([sys.executable, str(RUNNER_PATH)], capture_output=True, text=True) + self.assertNotEqual(proc.returncode, 0) + + def test_dry_run_lists_selected_jobs(self): + proc = subprocess.run([sys.executable, str(RUNNER_PATH), "R0.3", "--dry-run"], capture_output=True, text=True) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + self.assertIn("r03-engine-synthetic", proc.stdout) + + def test_timeout_cleanup_parent_and_child_running(self): + with tempfile.TemporaryDirectory() as td: + run_dir = Path(td) + pidfile = run_dir / "child.pid" + cmd = [sys.executable, "-c", + "import subprocess,sys,time,os;" + "p=subprocess.Popen([sys.executable,'-c','import time; time.sleep(60)']);" + f"open(r'{pidfile}','w').write(str(p.pid));" + "time.sleep(60)"] + job = self.make_job(command=cmd, timeout=2) + r = self.runner.run_job(job, run_dir) + self.assertEqual(r.status, "TIMEOUT") + self.assertTrue(pidfile.exists()) + child_pid = int(pidfile.read_text().strip()) + for _ in range(30): + try: + os.kill(child_pid, 0) + time.sleep(0.1) + except ProcessLookupError: + break + else: + self.fail(f"child still alive {child_pid}") + + def test_cleanup_parent_exited_child_still_running(self): + with tempfile.TemporaryDirectory() as td: + run_dir = Path(td) + pidfile = run_dir / "grandchild.pid" + # Direct child spawns a grandchild in same process group, writes pid, exits. + cmd = [sys.executable, "-c", + "import subprocess,sys,time;" + "p=subprocess.Popen([sys.executable,'-c','import time; time.sleep(60)']);" + f"open(r'{pidfile}','w').write(str(p.pid));"] + job = self.make_job(command=cmd, timeout=10) + r = self.runner.run_job(job, run_dir) + self.assertEqual(r.status, "FAIL") + self.assertEqual(r.exit_code, 0) + self.assertIn("cleaned surviving descendants", r.message) + self.assertTrue(pidfile.exists()) + gpid = int(pidfile.read_text().strip()) + self.assert_process_finished(gpid, "zero-exit descendant cleanup") + + def test_nonzero_parent_with_surviving_child_fails_and_cleans_up(self): + with tempfile.TemporaryDirectory() as td: + run_dir = Path(td) + pidfile = run_dir / "child.pid" + cmd = [sys.executable, "-c", + "import subprocess,sys;" + "p=subprocess.Popen([sys.executable,'-c','import time; time.sleep(60)']);" + f"open(r'{pidfile}','w').write(str(p.pid));sys.exit(7)"] + r = self.runner.run_job(self.make_job(command=cmd), run_dir) + self.assertEqual((r.status, r.exit_code), ("FAIL", 7)) + self.assertIn("cleaned surviving descendants", r.message) + self.assert_process_finished(int(pidfile.read_text()), "nonzero descendant cleanup") + + def test_timeout_child_ignores_sigterm(self): + with tempfile.TemporaryDirectory() as td: + run_dir = Path(td) + pidfile = run_dir / "child.pid" + cmd = [sys.executable, "-c", + "import subprocess,time,sys;" + "p=subprocess.Popen([sys.executable,'-c'," + "'import signal,time; signal.signal(signal.SIGTERM,signal.SIG_IGN); time.sleep(60)']);" + f"open(r'{pidfile}','w').write(str(p.pid));" + "time.sleep(60)"] + job = self.make_job(command=cmd, timeout=2) + start = time.time() + r = self.runner.run_job(job, run_dir) + self.assertEqual(r.status, "TIMEOUT") + self.assertLess(time.time() - start, 20) + if pidfile.exists(): + pid = int(pidfile.read_text().strip()) + self.assert_process_finished(pid, "SIGKILL escalation") + + def test_kill_process_group_already_gone(self): + # Should be a no-op / not raise. + proc = subprocess.Popen([sys.executable, "-c", "pass"], start_new_session=True) + proc.wait(timeout=10) + pgid = proc.pid + # group may or may not be gone; call should be safe either way + self.runner.kill_process_group(proc, pgid) + self.runner.kill_process_group(proc, pgid) + + def test_zombie_is_not_a_running_process_group(self): + proc = subprocess.Popen([sys.executable, "-c", "pass"], start_new_session=True) + info = self.runner._process_info(proc.pid) + self.assertIsNotNone(info) + start = info[3] + time.sleep(0.1) + self.assertFalse(self.runner._group_alive(proc.pid, start)) + proc.wait(timeout=5) + + def test_reused_leader_identity_is_not_targeted(self): + proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"], + start_new_session=True) + info = self.runner._process_info(proc.pid) + self.assertIsNotNone(info) + start = info[3] + self.assertEqual(self.runner._process_group_members(proc.pid, start + 1), []) + self.assertIsNone(proc.poll()) + self.runner.kill_process_group(proc, proc.pid, start) + self.assertIsNotNone(proc.returncode) diff --git a/tests/ui_tests.c b/tests/ui_tests.c new file mode 100644 index 00000000..6cf0faa6 --- /dev/null +++ b/tests/ui_tests.c @@ -0,0 +1,122 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/WL_MAIN.h" +#include "engine/WL_DEF.h" +#include "engine/WL_MENU.h" +#include "engine/ID_CA.h" +#include "engine/ID_VH.h" +#include "engine/ID_US_1.h" +#include "engine/ID_IN.h" +#include "engine/ID_TIME.h" +#include +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"%s:%d: %s (%s)\n",__FILE__,__LINE__,#x,CA_Error()); exit(1); } } while (0) +static void Key(unsigned scan) { IN_KeyEvent(scan,true); IN_KeyEvent(scan,false); } +static void TestClockAndFade(void) +{ + CHECK(TimeCount_FromNS(0) == 0); + CHECK(TimeCount_FromNS(1000000000) == 70); + CHECK(TimeCount_FromNS(14285714) == 0 && TimeCount_FromNS(14285715) == 1); + CHECK(TimeCount_FromNS(UINT64_MAX) == UINT64_C(1291272085159)); + w3r_byte gray[768]; memset(gray,31,sizeof(gray)); + CHECK(VL_SetPalette(gray,768)); + CHECK(VL_FadeOut(0,0,0,3,100)); + VL_FadeStep(99); CHECK(palette[0] == 31); + VL_FadeStep(101); CHECK(palette[0] == 21 && VL_Fading()); + VL_FadeStep(102); CHECK(palette[0] == 11); + VL_FadeStep(103); CHECK(palette[0] == 0 && !VL_Fading()); + CHECK(VL_FadeIn(gray,3,103)); + VL_FadeStep(104); CHECK(palette[0] == 10); + VL_FadeStep(106); CHECK(palette[0] == 31 && !VL_Fading()); + CHECK(!VL_FadeOut(64,0,0,3,0) && !VL_FadeIn(gray,1001,0)); + CHECK(VL_FadeOut(0,0,0,0,0)); +} +static void TestInput(void) +{ + IN_ClearKeysDown(); IN_KeyEvent(0x1e,true); + CHECK(Keyboard[0x1e] && LastScan == 0x1e && LastASCII == 'a'); + CHECK(IN_ConsumePress(0x1e)); + IN_KeyEvent(0x1e,true); CHECK(!IN_ConsumePress(0x1e)); + IN_KeyEvent(0x1e,false); CHECK(!Keyboard[0x1e]); + Key(sc_Enter); CHECK(!Keyboard[sc_Enter] && IN_ConsumePress(sc_Enter)); + IN_KeyEvent(999,true); CHECK(!IN_ConsumePress(999)); + IN_ClearKeysDown(); CHECK(!IN_AnyPressed()); +} +static void TestDraw(bool synthetic) +{ + CHECK(VW_ValidateFont(0) && VW_ValidateFont(1)); + MainItems.curpos = viewscores; + CHECK(SetupControlPanel(0)); + CHECK(framebuffer[199*320] == BORDCOLOR && framebuffer[12*320] == 0); + CHECK(framebuffer[32*320] == STRIPE && framebuffer[54*320+69] == BKGDCOLOR); + if (synthetic) { + CHECK(framebuffer[80] == C_OPTIONSPIC); + CHECK(framebuffer[(53+6*13)*320+72] == C_CURSOR1PIC); + } + fontnumber = 1; fontcolor = 19; + int w,h; CHECK(VW_MeasurePropString("A",&w,&h)); + VWB_Bar(0,0,320,200,45); px = 3; py = 4; + CHECK(VW_DrawPropString("A")); + if (synthetic) { + CHECK(w == 5 && h == 13); + for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) + CHECK(framebuffer[(4+y)*320+3+x] == ((x+y+65)%3 ? 19 : 45)); + } + PrintX = WindowX = 3; PrintY = 4; + CHECK(US_Print("A\nA")); CHECK(PrintX == 3+w && PrintY == 4+h); + w3r_byte *font = grsegs[2]; + w3r_byte low = font[0], high = font[1]; + font[0] = font[1] = 0; CHECK(!VW_ValidateFont(1)); font[0] = low; font[1] = high; + size_t size = grsizes[2]; grsizes[2] = 769; CHECK(!VW_ValidateFont(1)); grsizes[2] = size; + size_t at = 2+65*2; low = font[at]; high = font[at+1]; + font[at] = font[at+1] = 255; CHECK(!VW_ValidateFont(1)); font[at] = low; font[at+1] = high; + CHECK(DrawHighScores() && DrawMainMenu()); +} +static void TestAttract(void) +{ + CHECK(DemoLoopStartup(0,false)); CHECK(DemoLoopState() == UI_TITLE && palette[5] == 0); + CHECK(DemoLoop(30)); CHECK(!VL_Fading()); + CHECK(DemoLoop(1079)); CHECK(DemoLoopState() == UI_TITLE); + CHECK(DemoLoop(1080)); CHECK(DemoLoopState() == UI_TITLE && VL_Fading()); + CHECK(DemoLoop(1110)); CHECK(DemoLoopState() == UI_CREDITS); + CHECK(DemoLoop(1870)); CHECK(DemoLoopState() == UI_HIGHSCORES); + CHECK(DemoLoop(2640)); CHECK(DemoLoopState() == UI_TITLE || DemoLoopState() == UI_DEMO); + CHECK(DemoLoopStartup(2630,true)); CHECK(DemoLoop(2640)); + MainItems.curpos = viewscores; + IN_KeyEvent(sc_DownArrow,true); CHECK(DemoLoop(2640)); CHECK(MainItems.curpos == backtodemo); + CHECK(DemoLoop(2659)); CHECK(MainItems.curpos == backtodemo); + CHECK(DemoLoop(2660)); CHECK(MainItems.curpos == quit); + IN_KeyEvent(sc_DownArrow,false); CHECK(DemoLoop(2661)); + Key(sc_DownArrow); CHECK(DemoLoop(2662)); CHECK(MainItems.curpos == control); + Key(sc_UpArrow); CHECK(DemoLoop(2663)); CHECK(MainItems.curpos == quit); + Key(0x2f); CHECK(DemoLoop(2664)); CHECK(MainItems.curpos == viewscores); /* V shortcut */ + Key(sc_Enter); CHECK(DemoLoop(2665)); CHECK(DemoLoop(2685)); CHECK(DemoLoopState() == UI_SCORES); + Key(sc_Escape); CHECK(DemoLoop(2686)); CHECK(DemoLoop(2706)); CHECK(DemoLoopState() == UI_MENU); + Key(sc_Escape); CHECK(DemoLoop(2707)); CHECK(DemoLoopState() == UI_CONFIRM); + Key(sc_N); CHECK(DemoLoop(2708)); CHECK(DemoLoopState() == UI_MENU); + Key(0x30); CHECK(DemoLoop(2709)); CHECK(MainItems.curpos == backtodemo); /* B shortcut */ + Key(sc_Enter); CHECK(DemoLoop(2710)); CHECK(DemoLoop(2720)); CHECK(DemoLoopState() == UI_TITLE); + Key(sc_Enter); CHECK(DemoLoop(2721)); CHECK(DemoLoop(2761)); CHECK(DemoLoopState() == UI_MENU); + Key(0x10); CHECK(DemoLoop(2762)); CHECK(MainItems.curpos == quit); /* Q shortcut */ + Key(sc_Enter); CHECK(DemoLoop(2763)); CHECK(DemoLoopState() == UI_CONFIRM); + Key(sc_Y); CHECK(DemoLoop(2764)); CHECK(DemoLoop(2774)); CHECK(DemoLoopState() == UI_DONE); + /* A single coarse clock update reaches the same menu; no frame-count timing. */ + CHECK(DemoLoopStartup(0,false) && DemoLoop(2640)); CHECK(DemoLoopState() == UI_TITLE || DemoLoopState() == UI_DEMO); + GameStop(); + MainItems.curpos = viewscores; CHECK(SetupControlPanel(0)); IN_ClearKeysDown(); + IN_KeyEvent(sc_DownArrow,true); CHECK(HandleMenu(0) == -2); IN_ClearPressed(); + CHECK(HandleMenu(60) == -2); int coarse = MainItems.curpos; + MainItems.curpos = viewscores; CHECK(SetupControlPanel(0)); IN_ClearKeysDown(); + IN_KeyEvent(sc_DownArrow,true); CHECK(HandleMenu(0) == -2); IN_ClearPressed(); + for (uint64_t t = 20; t <= 60; t += 20) CHECK(HandleMenu(t) == -2); + CHECK(MainItems.curpos == coarse); IN_ClearKeysDown(); +} +int main(int argc, char **argv) +{ + CHECK(argc >= 2); TestClockAndFade(); TestInput(); MM_Startup(); + CHECK(CA_Startup(argv[1])); CHECK(VL_SetPalette(gamepal,768)); + TestDraw(argc == 2); TestAttract(); + CA_Shutdown(); MM_Shutdown(); CHECK(!MM_TotalBytes()); + puts("Original UI drawing, malformed fonts, input, fades and 70 Hz attract/menu tests passed."); + return 0; +} diff --git a/tests/video_tests.c b/tests/video_tests.c new file mode 100644 index 00000000..70b6566d --- /dev/null +++ b/tests/video_tests.c @@ -0,0 +1,114 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#include "engine/ID_VL.h" +#include "platform/sdl_video.h" +#include "platform/sdl_input.h" +#include "engine/ID_IN.h" +#include +#include +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr, "%s:%d: %s: %s\n", __FILE__, __LINE__, #x, SDL_GetError()); exit(1); } } while (0) + +static void Pixel(SDL_Surface *surface, int x, int y, Uint8 r, Uint8 g, Uint8 b) +{ + Uint8 actual_r, actual_g, actual_b, a; + CHECK(SDL_ReadSurfacePixel(surface, x, y, &actual_r, &actual_g, &actual_b, &a)); + CHECK(actual_r == r && actual_g == g && actual_b == b && a == 255); +} + +int main(int argc, char **argv) +{ + w3r_byte colors[768] = {0}; + CHECK(argc == 2); + colors[3] = 63; colors[7] = 63; + CHECK(VL_SetPalette(colors, sizeof(colors))); + for (size_t i = 0; i < VL_PIXELS; ++i) framebuffer[i] = (i % 320 < 160) ? 1 : 2; + CHECK(VL_Startup()); + CHECK(VW_UpdateScreen()); + CHECK(VL_TextureUploads() == 1); + CHECK(VW_UpdateScreen() && VL_TextureUploads() == 1); + CHECK(VL_Capture(argv[1])); + SDL_Surface *surface = SDL_LoadBMP(argv[1]); + CHECK(surface && surface->w == 960 && surface->h == 720); + Pixel(surface, 0, 0, 255, 0, 0); + Pixel(surface, 959, 719, 0, 255, 0); + SDL_DestroySurface(surface); + int count; + SDL_Window **windows = SDL_GetWindows(&count); + CHECK(windows && count == 1); + SDL_Window *window = windows[0]; + CHECK(SDL_SetWindowSize(windows[0], 1000, 600)); + CHECK(SDL_SyncWindow(windows[0])); + SDL_Renderer *renderer = SDL_GetRenderer(windows[0]); + CHECK(renderer); + SDL_free(windows); + (void)VL_PollQuit(); + CHECK(VW_UpdateScreen()); + CHECK(VL_Capture(argv[1])); + surface = SDL_LoadBMP(argv[1]); + /* SDL readback clips to the logical viewport, excluding letterbox bars. */ + CHECK(surface && surface->w == 800 && surface->h == 600); + SDL_FRect rect; + CHECK(SDL_GetRenderLogicalPresentationRect(renderer, &rect)); + CHECK(rect.x == 100 && rect.y == 0 && rect.w == 800 && rect.h == 600); + for (int x = 0; x < 800; ++x) + Pixel(surface, x, 300, x < 400 ? 255 : 0, x < 400 ? 0 : 255, 0); + SDL_DestroySurface(surface); + /* A palette-only update must recolor an unchanged indexed framebuffer. */ + colors[3] = 0; colors[5] = 63; + CHECK(VL_SetPalette(colors, sizeof(colors)) && VL_Capture(argv[1])); + surface = SDL_LoadBMP(argv[1]); CHECK(surface); + Pixel(surface, 0, 300, 0, 0, 255); + SDL_DestroySurface(surface); + CHECK(SDL_SetWindowSize(window, 600, 1000)); + CHECK(SDL_SyncWindow(window)); + (void)VL_PollQuit(); + CHECK(VW_UpdateScreen() && VL_Capture(argv[1])); + CHECK(SDL_GetRenderLogicalPresentationRect(renderer, &rect)); + CHECK(rect.x == 0 && rect.y == 275 && rect.w == 600 && rect.h == 450); + surface = SDL_LoadBMP(argv[1]); + CHECK(surface && surface->w == 600 && surface->h == 450); + Pixel(surface, 0, 0, 0, 0, 255); + Pixel(surface, 599, 449, 0, 255, 0); + SDL_DestroySurface(surface); + SDL_Event event; memset(&event, 0, sizeof(event)); + event.type = SDL_EVENT_KEY_DOWN; event.key.scancode = SDL_SCANCODE_ESCAPE; + CHECK(SDL_PushEvent(&event)); CHECK(!VL_PollQuit()); + CHECK(Keyboard[sc_Escape] && IN_ConsumePress(sc_Escape)); + event.type = SDL_EVENT_KEY_UP; + CHECK(SDL_PushEvent(&event)); CHECK(!VL_PollQuit()); CHECK(!Keyboard[sc_Escape]); + CHECK(IN_MapSDLScancode(SDL_SCANCODE_A) == 0x1e); + CHECK(IN_MapSDLScancode(SDL_SCANCODE_Z) == 0x2c); + CHECK(IN_MapSDLScancode(SDL_SCANCODE_UP) == sc_UpArrow); + CHECK(IN_MapSDLScancode(SDL_SCANCODE_KP_ENTER) == sc_Enter); + CHECK(IN_MapSDLScancode(99999) == 0); + IN_SDLKey(SDL_SCANCODE_LCTRL,true); IN_SDLKey(SDL_SCANCODE_RCTRL,true); + IN_SDLKey(SDL_SCANCODE_LCTRL,false); CHECK(Keyboard[0x1d]); + IN_SDLKey(SDL_SCANCODE_RCTRL,false); CHECK(!Keyboard[0x1d]); + event.type = SDL_EVENT_KEY_DOWN; event.key.scancode = SDL_SCANCODE_DOWN; + CHECK(SDL_PushEvent(&event)); CHECK(!VL_PollQuit()); + CHECK(Keyboard[sc_DownArrow] && IN_ConsumePress(sc_DownArrow)); + event.key.repeat = true; + CHECK(SDL_PushEvent(&event)); CHECK(!VL_PollQuit()); CHECK(!IN_ConsumePress(sc_DownArrow)); + event.type = SDL_EVENT_WINDOW_FOCUS_LOST; + CHECK(SDL_PushEvent(&event)); CHECK(!VL_PollQuit()); CHECK(!Keyboard[sc_DownArrow]); + CHECK(!IN_AnyPressed()); + event.type = SDL_EVENT_QUIT; + CHECK(SDL_PushEvent(&event)); CHECK(VL_PollQuit()); + CHECK(VL_TextureUploads() == 2); /* Resize needs no new upload; palette change does. */ + VL_Shutdown(); + for (int n = 0; n < 3; ++n) { + CHECK(VL_Startup()); CHECK(VW_UpdateScreen()); VL_Shutdown(); VL_Shutdown(); + CHECK(SDL_WasInit(SDL_INIT_VIDEO) == 0); + } + CHECK(SDL_setenv_unsafe("SDL_RENDER_DRIVER","no-such-renderer",1) == 0); + for (int n = 0; n < 2; ++n) { + CHECK(!VL_Startup()); CHECK(VL_Error()[0]); + CHECK(SDL_WasInit(SDL_INIT_VIDEO) == 0); + windows = SDL_GetWindows(&count); CHECK(count == 0); SDL_free(windows); + } + CHECK(SDL_setenv_unsafe("SDL_RENDER_DRIVER","software",1) == 0); + CHECK(VL_Startup()); CHECK(VW_UpdateScreen()); VL_Shutdown(); + puts("SDL3 render readback, 4:3 resize/letterbox, nearest colors, palette update and Escape passed."); + return 0; +} diff --git a/tests/visual_baseline.py b/tests/visual_baseline.py new file mode 100644 index 00000000..8195d719 --- /dev/null +++ b/tests/visual_baseline.py @@ -0,0 +1,270 @@ +"""Dependency-free Wolf3D indexed-capture manifest and comparison helpers.""" +from __future__ import annotations + +from dataclasses import dataclass +import hashlib +import json +from pathlib import Path +import struct +import zipfile + +SCHEMA_VERSION = 1 +FORMAT = "w3r-indexed-v1" +SOURCE_REVISION = "R0.4-baseline-v1" + + +@dataclass(frozen=True) +class IndexedCapture: + width: int + height: int + pixels: bytes + + +@dataclass(frozen=True) +class Difference: + changed_pixels: int + bounding_box: tuple[int, int, int, int] | None + + +def _read_indexed_data(data: bytes, label: str) -> IndexedCapture: + if len(data) < 16 or data[:4] != b"W3RI": + raise ValueError(f"{label}: not a {FORMAT} capture") + version, width, height = struct.unpack_from(" 8192 or height > 8192: + raise ValueError(f"{label}: invalid dimensions {width}x{height}") + expected = 16 + width * height + if len(data) != expected: + raise ValueError(f"{label}: expected {expected} bytes, found {len(data)}") + return IndexedCapture(width, height, data[16:]) + + +def read_indexed(path: Path) -> IndexedCapture: + return _read_indexed_data(path.read_bytes(), str(path)) + + +def compare_pixels(expected: IndexedCapture, actual: IndexedCapture) -> Difference: + if (expected.width, expected.height) != (actual.width, actual.height): + raise ValueError( + f"dimension mismatch: expected {expected.width}x{expected.height}, " + f"found {actual.width}x{actual.height}" + ) + changed = 0 + min_x, min_y = actual.width, actual.height + max_x = max_y = -1 + for offset, (left, right) in enumerate(zip(expected.pixels, actual.pixels)): + if left == right: + continue + changed += 1 + x, y = offset % actual.width, offset // actual.width + min_x, min_y = min(min_x, x), min(min_y, y) + max_x, max_y = max(max_x, x), max(max_y, y) + box = None if not changed else (min_x, min_y, max_x, max_y) + return Difference(changed, box) + + +def require_exact_pixels(expected: IndexedCapture, actual: IndexedCapture, + label: str = "capture") -> None: + difference = compare_pixels(expected, actual) + if difference.changed_pixels: + raise ValueError( + f"{label}: pixel mismatch; changed_pixels={difference.changed_pixels}, " + f"bounding_box={difference.bounding_box}" + ) + + +def compare_metadata(expected: dict, actual: dict) -> None: + if expected != actual: + keys = sorted(set(expected) | set(actual)) + changed = [key for key in keys if expected.get(key) != actual.get(key)] + details = ", ".join( + f"{key}: {expected.get(key)!r} != {actual.get(key)!r}" for key in changed + ) + raise ValueError(f"metadata mismatch: {details}") + + +def fixture_identity(data_directory: Path) -> str: + digest = hashlib.sha256() + for path in sorted(p for p in data_directory.iterdir() if p.is_file()): + digest.update(path.name.encode("utf-8") + b"\0") + digest.update(path.read_bytes()) + return "sha256:" + digest.hexdigest() + + +def _spec(name: str) -> dict: + parts = name.split("-") + mode = "classic" if "classic" in parts else "enhanced" + scene = next(scene for scene in ( + "corridor-static", "door-motion", "pushwall-motion", + "edge-clipping", "display-transition" + ) if name.startswith(scene)) + state = "static" + for value in ("closed", "half-open", "open", "initial", "moving", + "tile-boundary", "letterbox", "resize", "restored", "wide", "auto"): + if f"-{value}-" in f"-{name}-": + state = value + break + dimensions = next(part for part in parts if "x" in part and part.replace("x", "").isdigit()) + width, height = map(int, dimensions.split("x")) + aspect = "4:3" if mode == "classic" else "auto" + for token, value in (("4x3", "4:3"), ("16x9", "16:9"), ("16x10", "16:10"), + ("21x9", "21:9"), ("32x9", "32:9")): + if token in parts: + aspect = value + if mode == "enhanced" and aspect == "auto" and "auto" not in parts: + aspect = "16:9" + world_state = {"random_seed": 0, "view_size": 15, "weapon": "pistol"} + if scene == "door-motion": + world_state["door"] = {"tile": [9, 3], "position": { + "closed": 0, "half-open": 32768, "open": 65535 + }[state]} + if scene == "pushwall-motion": + world_state["pushwall"] = { + "initial": {"tile": [8, 3], "state": 1, "position": 0}, + "moving": {"tile": [8, 3], "state": 64, "position": 32}, + "tile-boundary": {"tile": [9, 3], "state": 128, "position": 0}, + }[state] + return { + "scene_id": scene, + "rendering_mode": mode, + "state": state, + "simulation_tick": 0, + "camera": {"tile": [2, 3], "offset": [32768, 32768], "angle": 0}, + "world_state": world_state, + "internal_dimensions": [320, 200] if mode == "classic" else [width, height], + "output_dimensions": [width, height], + "aspect_ratio": aspect, + "sdl_backend": "not-applicable-canonical-indexed", + "capture_method": "classic-framebuffer" if mode == "classic" and dimensions == "320x200" + else "classic-corrected-nearest" if mode == "classic" + else "WL_RenderFrameAspect", + "pixel_format": FORMAT, + "comparison_policy": "exact-indexed", + } + + +def capture_manifest(capture_directory: Path, data_directory: Path) -> dict: + palette = capture_directory / "palette.rgb6" + palette_bytes = palette.read_bytes() + if len(palette_bytes) != 768: + raise ValueError(f"{palette}: expected 768 palette bytes, found {len(palette_bytes)}") + entries = [] + for path in sorted(capture_directory.glob("*.w3i")): + capture = read_indexed(path) + metadata = _spec(path.stem) + if metadata["output_dimensions"] != [capture.width, capture.height]: + raise ValueError(f"{path}: filename dimensions disagree with capture header") + metadata.update({ + "id": path.stem, + "fixture_identity": fixture_identity(data_directory), + "source_revision": SOURCE_REVISION, + "palette_identity": "sha256:" + hashlib.sha256(palette_bytes).hexdigest(), + "pixel_hash": "sha256:" + hashlib.sha256(capture.pixels).hexdigest(), + }) + entries.append(metadata) + if not entries: + raise ValueError(f"{capture_directory}: no indexed captures produced") + return {"schema_version": SCHEMA_VERSION, "captures": entries} + + +def validate_manifest(actual: dict, expected_path: Path, capture_directory: Path, + archive_path: Path) -> None: + expected = json.loads(expected_path.read_text(encoding="utf-8")) + if expected.get("schema_version") != actual.get("schema_version"): + raise ValueError("metadata mismatch: manifest schema version") + expected_entries = {entry["id"]: entry for entry in expected["captures"]} + actual_entries = {entry["id"]: entry for entry in actual["captures"]} + if expected_entries.keys() != actual_entries.keys(): + raise ValueError("metadata mismatch: capture ID set") + with zipfile.ZipFile(archive_path) as archive: + names = archive.namelist() + if len(names) != len(set(names)): + duplicates = sorted(name for name in set(names) if names.count(name) > 1) + raise ValueError(f"baseline archive: duplicate entries {duplicates}") + unexpected_names = sorted( + name for name in names + if not name.endswith(".w3i") or "/" in name or "\\" in name + ) + if unexpected_names: + raise ValueError(f"baseline archive: unexpected entries {unexpected_names}") + archived_ids = {name[:-4] for name in names} + missing = sorted(expected_entries.keys() - archived_ids) + unexpected = sorted(archived_ids - expected_entries.keys()) + if missing or unexpected: + raise ValueError( + f"baseline archive: capture ID set; missing={missing}, " + f"unexpected={unexpected}" + ) + baselines = {} + for capture_id in sorted(expected_entries): + entry = expected_entries[capture_id] + baseline = _read_indexed_data(archive.read(capture_id + ".w3i"), capture_id) + dimensions = entry["output_dimensions"] + if not isinstance(dimensions, (list, tuple)) or len(dimensions) != 2: + raise ValueError(f"{capture_id}: invalid manifest dimensions {dimensions!r}") + if [baseline.width, baseline.height] != list(dimensions): + raise ValueError( + f"{capture_id}: archived dimension mismatch; " + f"expected={dimensions[0]}x{dimensions[1]}, " + f"actual={baseline.width}x{baseline.height}" + ) + expected_hash = entry["pixel_hash"] + archived_hash = "sha256:" + hashlib.sha256(baseline.pixels).hexdigest() + if archived_hash != expected_hash: + raise ValueError( + f"{capture_id}: archived baseline hash mismatch; " + f"expected={expected_hash}, actual={archived_hash}" + ) + baselines[capture_id] = baseline + for capture_id in sorted(expected_entries): + left, right = dict(expected_entries[capture_id]), dict(actual_entries[capture_id]) + expected_hash, actual_hash = left.pop("pixel_hash"), right.pop("pixel_hash") + compare_metadata(left, right) + candidate = read_indexed(capture_directory / (capture_id + ".w3i")) + difference = compare_pixels(baselines[capture_id], candidate) + if difference.changed_pixels or expected_hash != actual_hash: + raise ValueError( + f"{capture_id}: pixel mismatch; changed_pixels=" + f"{difference.changed_pixels}, bounding_box={difference.bounding_box}, " + f"expected={expected_hash}, actual={actual_hash}" + ) + + +def write_manifest(path: Path, manifest: dict) -> None: + path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + +def write_baseline_archive(path: Path, capture_directory: Path) -> None: + with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: + for capture in sorted(capture_directory.glob("*.w3i")): + info = zipfile.ZipInfo(capture.name, date_time=(1980, 1, 1, 0, 0, 0)) + info.compress_type = zipfile.ZIP_DEFLATED + info.external_attr = 0o100644 << 16 + archive.writestr(info, capture.read_bytes(), compresslevel=9) + + +def write_bmp(path: Path, capture: IndexedCapture, palette_rgb6: bytes) -> None: + row_size = (capture.width + 3) & ~3 + pixel_size = row_size * capture.height + offset = 14 + 40 + 256 * 4 + header = struct.pack("<2sIHHI", b"BM", offset + pixel_size, 0, 0, offset) + dib = struct.pack("> 4) + colors.extend((expand(blue), expand(green), expand(red), 0)) + padding = b"\0" * (row_size - capture.width) + with path.open("wb") as output: + output.write(header + dib + colors) + for y in range(capture.height - 1, -1, -1): + start = y * capture.width + output.write(capture.pixels[start:start + capture.width] + padding) + + +def create_review_bmps(capture_directory: Path) -> None: + palette = (capture_directory / "palette.rgb6").read_bytes() + for indexed in sorted(capture_directory.glob("*.w3i")): + write_bmp(indexed.with_suffix(".bmp"), read_indexed(indexed), palette) diff --git a/third_party/emu8950/LICENSE b/third_party/emu8950/LICENSE new file mode 100644 index 00000000..e688c461 --- /dev/null +++ b/third_party/emu8950/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Mitsutaka Okazaki + +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. diff --git a/third_party/emu8950/README.wolf3d.md b/third_party/emu8950/README.wolf3d.md new file mode 100644 index 00000000..09d59551 --- /dev/null +++ b/third_party/emu8950/README.wolf3d.md @@ -0,0 +1,27 @@ +# emu8950 provenance + +Upstream: https://github.com/digital-sound-antiques/emu8950 + +Pinned commit: `f82a22e80b68820f263084aa8506b12eb1c9b4dd` (source identifies +itself as emu8950 v1.2.3). Downloaded directly from that commit, 2026-11-02. +`LICENSE` is upstream's MIT licence; retain it and all source notices. +The active Wolf3D port remains GPL-2.0-only, with this MIT dependency. + +Imported files: `emu8950.c`, `emu8950.h`, `emuadpcm.c`, `emuadpcm.h`, `LICENSE`. +The ADPCM module is needed to link upstream's API, but Wolf selects YM3812 +and never uses Y8950 ADPCM, DOS, DMA or Sound Blaster hardware emulation. + +Two local safety patches: + +- `emuadpcm.c`: zero-initialize the object with `calloc`, so partial allocation + failure can safely free either buffer during initial chip creation. +- `emu8950.c:lookup_exp_table`: replace a left shift of a potentially negative + integer with multiplication by two and an explicit result cast. UBSan found + this with owned music and the synthetic test instrument. The bounded result + fits in int16_t and the intended sample values are preserved. + +`src/engine/ID_OPL*.c` compile each implementation as a separate translation +unit. GCC conversion/shadow/unused-parameter/pedantic warnings are suppressed +only around these imported files. The port itself is checked with strict +warnings as errors. No synthesis code is generated or downloaded at build +or launch. See `docs/MILESTONE6B.md` for selection and fidelity limitations. diff --git a/third_party/emu8950/emu8950.c b/third_party/emu8950/emu8950.c new file mode 100644 index 00000000..f92a156c --- /dev/null +++ b/third_party/emu8950/emu8950.c @@ -0,0 +1,1414 @@ +/** + * emu8950 v1.2.3 + * https://github.com/digital-sound-antiques/emu8950 + * Copyright (C) 2001-2026 Mitsutaka Okazaki + */ +#include "emu8950.h" +#include +#include +#include +#include + +#ifndef INLINE +#if defined(_MSC_VER) +#define INLINE __inline +#elif defined(__GNUC__) +#define INLINE __inline__ +#else +#define INLINE inline +#endif +#endif + +#define _PI_ 3.14159265358979323846264338327950288 + +enum __OPL_EG_STATE { ATTACK, DECAY, SUSTAIN, RELEASE, UNKNOWN }; +enum __OPL_TYPE { TYPE_Y8950 = 0, TYPE_YM3526, TYPE_YM3812, TYPE_MAX }; + +/* phase increment counter */ +#define DP_BITS 20 +#define DP_WIDTH (1 << DP_BITS) +#define DP_BASE_BITS (DP_BITS - PG_BITS) + +/* dynamic range of envelope output */ +#define EG_STEP 0.1875 +#define EG_BITS 9 +#define EG_MUTE ((1 << EG_BITS) - 1) +#define EG_MAX (0x1f0) // 93dB + +/* dynamic range of total level */ +#define TL_STEP 0.75 +#define TL_BITS 6 + +/* dynamic range of sustine level */ +#define SL_STEP 3.0 +#define SL_BITS 4 + +#define TL2EG(tl) ((tl) << 2) + +/* sine table */ +#define PG_BITS 10 /* 2^10 = 1024 length sine table */ +#define PG_WIDTH (1 << PG_BITS) + +/* clang-format off */ +/* exp_table[x] = round((exp2((double)x / 256.0) - 1) * 1024) */ +static uint16_t exp_table[256] = { +0, 3, 6, 8, 11, 14, 17, 20, 22, 25, 28, 31, 34, 37, 40, 42, +45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, +93, 96, 99, 102, 105, 108, 111, 114, 117, 120, 123, 126, 130, 133, 136, 139, +142, 145, 148, 152, 155, 158, 161, 164, 168, 171, 174, 177, 181, 184, 187, 190, +194, 197, 200, 204, 207, 210, 214, 217, 220, 224, 227, 231, 234, 237, 241, 244, +248, 251, 255, 258, 262, 265, 268, 272, 276, 279, 283, 286, 290, 293, 297, 300, +304, 308, 311, 315, 318, 322, 326, 329, 333, 337, 340, 344, 348, 352, 355, 359, +363, 367, 370, 374, 378, 382, 385, 389, 393, 397, 401, 405, 409, 412, 416, 420, +424, 428, 432, 436, 440, 444, 448, 452, 456, 460, 464, 468, 472, 476, 480, 484, +488, 492, 496, 501, 505, 509, 513, 517, 521, 526, 530, 534, 538, 542, 547, 551, +555, 560, 564, 568, 572, 577, 581, 585, 590, 594, 599, 603, 607, 612, 616, 621, +625, 630, 634, 639, 643, 648, 652, 657, 661, 666, 670, 675, 680, 684, 689, 693, +698, 703, 708, 712, 717, 722, 726, 731, 736, 741, 745, 750, 755, 760, 765, 770, +774, 779, 784, 789, 794, 799, 804, 809, 814, 819, 824, 829, 834, 839, 844, 849, +854, 859, 864, 869, 874, 880, 885, 890, 895, 900, 906, 911, 916, 921, 927, 932, +937, 942, 948, 953, 959, 964, 969, 975, 980, 986, 991, 996, 1002, 1007, 1013, 1018 +}; +/* logsin_table[x] = round(-log2(sin((x + 0.5) * PI / (PG_WIDTH / 4) / 2)) * 256) */ +static uint16_t logsin_table[PG_WIDTH / 4] = { +2137, 1731, 1543, 1419, 1326, 1252, 1190, 1137, 1091, 1050, 1013, 979, 949, 920, 894, 869, +846, 825, 804, 785, 767, 749, 732, 717, 701, 687, 672, 659, 646, 633, 621, 609, +598, 587, 576, 566, 556, 546, 536, 527, 518, 509, 501, 492, 484, 476, 468, 461, +453, 446, 439, 432, 425, 418, 411, 405, 399, 392, 386, 380, 375, 369, 363, 358, +352, 347, 341, 336, 331, 326, 321, 316, 311, 307, 302, 297, 293, 289, 284, 280, +276, 271, 267, 263, 259, 255, 251, 248, 244, 240, 236, 233, 229, 226, 222, 219, +215, 212, 209, 205, 202, 199, 196, 193, 190, 187, 184, 181, 178, 175, 172, 169, +167, 164, 161, 159, 156, 153, 151, 148, 146, 143, 141, 138, 136, 134, 131, 129, +127, 125, 122, 120, 118, 116, 114, 112, 110, 108, 106, 104, 102, 100, 98, 96, +94, 92, 91, 89, 87, 85, 83, 82, 80, 78, 77, 75, 74, 72, 70, 69, +67, 66, 64, 63, 62, 60, 59, 57, 56, 55, 53, 52, 51, 49, 48, 47, +46, 45, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, +29, 28, 27, 26, 25, 24, 23, 23, 22, 21, 20, 20, 19, 18, 17, 17, +16, 15, 15, 14, 13, 13, 12, 12, 11, 10, 10, 9, 9, 8, 8, 7, +7, 7, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, +2, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, +}; +/* clang-format on */ + +static uint16_t wave_table_map[4][PG_WIDTH]; + +/* pitch modulator */ +#define PM_PG_BITS 3 +#define PM_PG_WIDTH (1 << PM_PG_BITS) +#define PM_DP_BITS 22 +#define PM_DP_WIDTH (1 << PM_DP_BITS) + +/* offset to fnum, rough approximation of 14 cents depth. */ +static int8_t pm_table[8][PM_PG_WIDTH] = { + {0, 0, 0, 0, 0, 0, 0, 0}, // fnum = 000xxxxx + {0, 0, 1, 0, 0, 0, -1, 0}, // fnum = 001xxxxx + {0, 1, 2, 1, 0, -1, -2, -1}, // fnum = 010xxxxx + {0, 1, 3, 1, 0, -1, -3, -1}, // fnum = 011xxxxx + {0, 2, 4, 2, 0, -2, -4, -2}, // fnum = 100xxxxx + {0, 2, 5, 2, 0, -2, -5, -2}, // fnum = 101xxxxx + {0, 3, 6, 3, 0, -3, -6, -3}, // fnum = 110xxxxx + {0, 3, 7, 3, 0, -3, -7, -3}, // fnum = 111xxxxx +}; + +/* amplitude lfo table */ +/* The following envelop pattern is verified on real YM2413. */ +/* each element repeates 64 cycles */ +static uint8_t am_table[210] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // + 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, // + 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, // + 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, // + 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, // + 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, // + 12, 12, 12, 12, 12, 12, 12, 12, // + 13, 13, 13, // + 12, 12, 12, 12, 12, 12, 12, 12, // + 11, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 10, 10, // + 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, // + 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, // + 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, // + 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, // + 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0}; + +/* envelope decay increment step table */ +static uint8_t eg_step_tables[4][8] = { + {0, 1, 0, 1, 0, 1, 0, 1}, + {0, 1, 0, 1, 1, 1, 0, 1}, + {0, 1, 1, 1, 0, 1, 1, 1}, + {0, 1, 1, 1, 1, 1, 1, 1}, +}; +static uint8_t eg_step_tables_fast[4][8] = { + {1, 1, 1, 1, 1, 1, 1, 1}, + {1, 1, 1, 2, 1, 1, 1, 2}, + {1, 2, 1, 2, 1, 2, 1, 2}, + {1, 2, 2, 2, 1, 2, 2, 2}, +}; + +static uint32_t ml_table[16] = {1, 1 * 2, 2 * 2, 3 * 2, 4 * 2, 5 * 2, 6 * 2, 7 * 2, + 8 * 2, 9 * 2, 10 * 2, 10 * 2, 12 * 2, 12 * 2, 15 * 2, 15 * 2}; + +#define dB2(x) ((x) * 2) +static double kl_table[16] = {dB2(0.000), dB2(9.000), dB2(12.000), dB2(13.875), dB2(15.000), dB2(16.125), + dB2(16.875), dB2(17.625), dB2(18.000), dB2(18.750), dB2(19.125), dB2(19.500), + dB2(19.875), dB2(20.250), dB2(20.625), dB2(21.000)}; + +static uint16_t tll_table[8 * 16][4]; +static int32_t rks_table[2][32][2]; + +#define min(i, j) (((i) < (j)) ? (i) : (j)) +#define max(i, j) (((i) > (j)) ? (i) : (j)) + +/*************************************************** + + Internal Sample Rate Converter + +****************************************************/ +/* Note: to disable internal rate converter, set clock/72 to output sampling rate. */ + +/* + * LW is truncate length of sinc(x) calculation. + * Lower LW is faster, higher LW results better quality. + * LW must be a non-zero positive even number, no upper limit. + * LW=16 or greater is recommended when upsampling. + * LW=8 is practically okay for downsampling. + */ +#define LW 16 + +/* number of phases between two input samples. must be a power of 2. */ +#define SINC_RESO_BITS 8 +#define SINC_RESO (1 << SINC_RESO_BITS) +#define SINC_AMP_BITS 12 + +// double hamming(double x) { return 0.54 - 0.46 * cos(2 * PI * x); } +static double blackman(double x) { return 0.42 - 0.5 * cos(2 * _PI_ * x) + 0.08 * cos(4 * _PI_ * x); } +static double sinc(double x) { return (x == 0.0 ? 1.0 : sin(_PI_ * x) / (_PI_ * x)); } +static double windowed_sinc(double x) { return blackman(0.5 + 0.5 * x / (LW / 2)) * sinc(x); } + +/* f_inp: input frequency. f_out: output frequencey, ch: number of channels */ +OPL_RateConv *OPL_RateConv_new(double f_inp, double f_out, int ch) { + OPL_RateConv *conv = malloc(sizeof(OPL_RateConv)); + int i; + + conv->ch = ch; + conv->f_ratio = f_inp / f_out; + conv->timer_step = (uint32_t)((conv->f_ratio - floor(conv->f_ratio)) * 4294967296.0); + conv->buf = malloc(sizeof(conv->buf[0]) * ch); + conv->pos = malloc(sizeof(conv->pos[0]) * ch); + for (i = 0; i < ch; i++) { + conv->buf[i] = malloc(sizeof(conv->buf[0][0]) * LW * 2); + } + + /* sinc_table[p * LW + k] is the coefficient for buf[k] at phase dn = p / SINC_RESO (0 <= p <= SINC_RESO). + The coefficients for p and SINC_RESO - p are the same in reverse order, but both are kept to avoid a branch. */ + conv->sinc_table = malloc(sizeof(conv->sinc_table[0]) * (SINC_RESO + 1) * LW); + for (i = 0; i < (SINC_RESO + 1) * LW; i++) { + const double x = fabs((i % LW) - (LW / 2 - 1) - (double)(i / LW) / SINC_RESO); + if (f_out < f_inp) { + /* for downsampling */ + conv->sinc_table[i] = (int16_t)((1 << SINC_AMP_BITS) * windowed_sinc(x / conv->f_ratio) / conv->f_ratio); + } else { + /* for upsampling */ + conv->sinc_table[i] = (int16_t)((1 << SINC_AMP_BITS) * windowed_sinc(x)); + } + } + + return conv; +} + +/* p is the output phase in SINC_RESO units (0 <= p <= SINC_RESO). */ +static INLINE int16_t rateconv_get(OPL_RateConv *conv, int ch, uint32_t p) { + const int16_t *buf = conv->buf[ch] + conv->pos[ch]; + const int16_t *coef = conv->sinc_table + p * LW; + int32_t sum = 0; + int k; + for (k = 0; k < LW; k++) { + sum += buf[k] * coef[k]; + } + return sum >> SINC_AMP_BITS; +} + +void OPL_RateConv_reset(OPL_RateConv *conv) { + int i; + conv->timer = 0; + for (i = 0; i < conv->ch; i++) { + conv->pos[i] = 0; + memset(conv->buf[i], 0, sizeof(conv->buf[i][0]) * LW * 2); + } +} + +/* put original data to this converter at f_inp. */ +void OPL_RateConv_putData(OPL_RateConv *conv, int ch, int16_t data) { + int16_t *buf = conv->buf[ch]; + int pos = conv->pos[ch]; + buf[pos] = buf[pos + LW] = data; + conv->pos[ch] = (pos + 1 == LW) ? 0 : pos + 1; +} + +/* get resampled data from this converter at f_out. */ +/* this function must be called f_out / f_inp times per one putData call. */ +int16_t OPL_RateConv_getData(OPL_RateConv *conv, int ch) { + conv->timer += conv->timer_step; + return rateconv_get(conv, ch, (uint32_t)(((uint64_t)conv->timer + (1u << (31 - SINC_RESO_BITS))) >> (32 - SINC_RESO_BITS))); +} + +void OPL_RateConv_delete(OPL_RateConv *conv) { + int i; + for (i = 0; i < conv->ch; i++) { + free(conv->buf[i]); + } + free(conv->buf); + free(conv->pos); + free(conv->sinc_table); + free(conv); +} + +/*************************************************** + + Create tables + +****************************************************/ +static void makeSinTable(void) { + int x; + + for (x = 0; x < PG_WIDTH; x++) { + if (x < PG_WIDTH / 4) { + wave_table_map[0][x] = logsin_table[x]; + } else if (x < PG_WIDTH / 2) { + wave_table_map[0][x] = logsin_table[PG_WIDTH / 2 - x - 1]; + } else { + wave_table_map[0][x] = 0x8000 | wave_table_map[0][PG_WIDTH - x - 1]; + } + } + + for (x = 0; x < PG_WIDTH; x++) { + if (x < PG_WIDTH / 2) { + wave_table_map[1][x] = wave_table_map[0][x]; + } else { + wave_table_map[1][x] = 0xfff; + } + } + + for (x = 0; x < PG_WIDTH; x++) { + if (x < PG_WIDTH / 2) { + wave_table_map[2][x] = wave_table_map[0][x]; + } else { + wave_table_map[2][x] = wave_table_map[0][x - PG_WIDTH / 2]; + } + } + + for (x = 0; x < PG_WIDTH; x++) { + if (x < PG_WIDTH / 4) { + wave_table_map[3][x] = wave_table_map[0][x]; + } else if (x < PG_WIDTH / 2) { + wave_table_map[3][x] = 0xfff; + } else if (x < PG_WIDTH * 3 / 4) { + wave_table_map[3][x] = wave_table_map[0][x - PG_WIDTH / 2]; + } else { + wave_table_map[3][x] = 0xfff; + } + } +} + +static void makeTllTable(void) { + + int32_t tmp; + int32_t fnum, block, KL, kx; + + for (fnum = 0; fnum < 16; fnum++) { + for (block = 0; block < 8; block++) { + for (KL = 0; KL < 4; KL++) { + kx = ((KL & 1) << 1) | ((KL >> 1) & 1); + if (KL == 0) { + tll_table[(block << 4) | fnum][KL] = 0; + } else { + tmp = (int32_t)(kl_table[fnum] - dB2(3.000) * (7 - block)); + if (tmp <= 0) + tll_table[(block << 4) | fnum][KL] = 0; + else + tll_table[(block << 4) | fnum][KL] = (uint16_t)((tmp >> (3 - kx)) / EG_STEP); + } + } + } + } +} + +static void makeRksTable(void) { + int fnum8, fnum9, blk; + int blk_fnum98; + for (fnum8 = 0; fnum8 < 2; fnum8++) + for (fnum9 = 0; fnum9 < 2; fnum9++) + for (blk = 0; blk < 8; blk++) { + blk_fnum98 = (blk << 2) | (fnum9 << 1) | fnum8; + rks_table[0][blk_fnum98][1] = (blk << 1) + fnum9; + rks_table[0][blk_fnum98][0] = blk >> 1; + rks_table[1][blk_fnum98][1] = (blk << 1) + (fnum9 & fnum8); + rks_table[1][blk_fnum98][0] = blk >> 1; + } +} + +static uint8_t table_initialized = 0; + +static void initializeTables() { + makeTllTable(); + makeRksTable(); + makeSinTable(); + table_initialized = 1; +} + +/********************************************************* + + Synthesizing + +*********************************************************/ +#define SLOT_BD1 12 +#define SLOT_BD2 13 +#define SLOT_HH 14 +#define SLOT_SD 15 +#define SLOT_TOM 16 +#define SLOT_CYM 17 + +/* utility macros */ +#define MOD(o, x) (&(o)->slot[(x) << 1]) +#define CAR(o, x) (&(o)->slot[((x) << 1) | 1]) +#define BIT(s, b) (((s) >> (b)) & 1) + +#if OPL_DEBUG +static void _debug_print_patch(OPL_SLOT *slot) { + OPL_PATCH *p = slot->patch; + printf("[slot#%d am:%d pm:%d eg:%d kr:%d ml:%d kl:%d tl:%d ws:%d fb:%d A:%d D:%d S:%d R:%d]\n", slot->number, // + p->AM, p->PM, p->EG, p->KR, p->ML, // + p->KL, p->TL, p->WS, p->FB, // + p->AR, p->DR, p->SL, p->RR); +} + +static char *_debug_eg_state_name(OPL_SLOT *slot) { + switch (slot->eg_state) { + case ATTACK: + return "attack"; + case DECAY: + return "decay"; + case SUSTAIN: + return "sustain"; + case RELEASE: + return "release"; + default: + return "unknown"; + } +} + +static INLINE void _debug_print_slot_info(OPL_SLOT *slot) { + char *name = _debug_eg_state_name(slot); + _debug_print_patch(slot); + printf("[slot#%d state:%s fnum:%03x rate:%d-%d]\n", slot->number, name, slot->blk_fnum, slot->eg_rate_h, + slot->eg_rate_l); + fflush(stdout); +} +#endif + +static INLINE int get_parameter_rate(OPL_SLOT *slot) { + switch (slot->eg_state) { + case ATTACK: + return slot->patch->AR; + case DECAY: + return slot->patch->DR; + case SUSTAIN: + return slot->patch->EG ? 0 : slot->patch->RR; + case RELEASE: + return slot->patch->RR; + default: + return 0; + } +} + +enum SLOT_UPDATE_FLAG { + UPDATE_WS = 1, + UPDATE_TLL = 2, + UPDATE_RKS = 4, + UPDATE_EG = 8, + UPDATE_ALL = 255, +}; + +static INLINE void request_update(OPL_SLOT *slot, int flag) { slot->update_requests |= flag; } + +static void commit_slot_update(OPL_SLOT *slot, uint8_t notesel) { + + if (slot->update_requests & UPDATE_WS) { + slot->wave_table = wave_table_map[slot->patch->WS & 3]; + } + + if (slot->update_requests & UPDATE_TLL) { + slot->tll = tll_table[slot->blk_fnum >> 6][slot->patch->KL] + TL2EG(slot->patch->TL); + } + + if (slot->update_requests & UPDATE_RKS) { + slot->rks = rks_table[notesel][slot->blk_fnum >> 8][slot->patch->KR]; + } + + if (slot->update_requests & (UPDATE_RKS | UPDATE_EG)) { + int p_rate = get_parameter_rate(slot); + + if (p_rate == 0) { + slot->eg_shift = 0; + slot->eg_rate_h = 0; + slot->eg_rate_l = 0; + } else { + slot->eg_rate_h = min(15, p_rate + (slot->rks >> 2)); + slot->eg_rate_l = slot->rks & 3; + if (slot->eg_state == ATTACK) { + slot->eg_shift = (0 < slot->eg_rate_h && slot->eg_rate_h < 12) ? (12 - slot->eg_rate_h) : 0; + } else { + slot->eg_shift = (slot->eg_rate_h < 12) ? (12 - slot->eg_rate_h) : 0; + } + } + } + +#if OPL_DEBUG + if (slot->last_eg_state != slot->eg_state) { + _debug_print_slot_info(slot); + slot->last_eg_state = slot->eg_state; + } +#endif + + slot->update_requests = 0; +} + +static void reset_slot(OPL_SLOT *slot, int number) { + slot->patch = &(slot->__patch); + memset(slot->patch, 0, sizeof(OPL_PATCH)); + slot->number = number; + slot->type = number % 2; + slot->pg_keep = 0; + slot->wave_table = wave_table_map[0]; + slot->pg_phase = 0; + slot->output[0] = 0; + slot->output[1] = 0; + slot->eg_state = RELEASE; + slot->eg_shift = 0; + slot->rks = 0; + slot->tll = 0; + slot->blk_fnum = 0; + slot->blk = 0; + slot->fnum = 0; + slot->pg_out = 0; + slot->eg_rate_h = 0; + slot->eg_rate_l = 0; + slot->eg_out = EG_MUTE; + slot->update_requests = 0; +} + +static INLINE void slotOn(OPL *opl, int i) { + OPL_SLOT *slot = &opl->slot[i]; + slot->rks = rks_table[opl->notesel][slot->blk_fnum >> 8][slot->patch->KR]; + if (min(15, slot->patch->AR + (slot->rks >> 2)) == 15) { + slot->eg_state = DECAY; + slot->eg_out = 0; + } else { + slot->eg_state = ATTACK; + } + if (!slot->pg_keep) { + slot->pg_phase = 0; + } + request_update(slot, UPDATE_EG); +} + +static INLINE void slotOff(OPL *opl, int i) { + OPL_SLOT *slot = &opl->slot[i]; + slot->eg_state = RELEASE; + request_update(slot, UPDATE_EG); +} + +static INLINE void update_key_status(OPL *opl) { + const uint8_t r14 = opl->reg[0xbd]; + const uint8_t rhythm_mode = BIT(r14, 5); + uint32_t new_slot_key_status = 0; + uint32_t updated_status; + int ch; + + if (opl->csm_mode && opl->csm_key_count) { + new_slot_key_status = 0x3ffff; + } + + for (ch = 0; ch < 9; ch++) + if (opl->reg[0xB0 + ch] & 0x20) + new_slot_key_status |= 3 << (ch * 2); + + if (rhythm_mode) { + if (r14 & 0x10) + new_slot_key_status |= 3 << SLOT_BD1; + + if (r14 & 0x01) + new_slot_key_status |= 1 << SLOT_HH; + + if (r14 & 0x08) + new_slot_key_status |= 1 << SLOT_SD; + + if (r14 & 0x04) + new_slot_key_status |= 1 << SLOT_TOM; + + if (r14 & 0x02) + new_slot_key_status |= 1 << SLOT_CYM; + } + + updated_status = opl->slot_key_status ^ new_slot_key_status; + + if (updated_status) { + int i; + for (i = 0; i < 18; i++) + if (BIT(updated_status, i)) { + if (BIT(new_slot_key_status, i)) { + slotOn(opl, i); + } else { + slotOff(opl, i); + } + } + } + + opl->slot_key_status = new_slot_key_status; +} + +/* set f-Nnmber ( fnum : 10bit ) */ +static INLINE void set_fnumber(OPL *opl, int ch, int fnum) { + OPL_SLOT *car = CAR(opl, ch); + OPL_SLOT *mod = MOD(opl, ch); + car->fnum = fnum; + car->blk_fnum = (car->blk_fnum & 0x1c00) | (fnum & 0x3ff); + mod->fnum = fnum; + mod->blk_fnum = (mod->blk_fnum & 0x1c00) | (fnum & 0x3ff); + request_update(car, UPDATE_EG | UPDATE_RKS | UPDATE_TLL); + request_update(mod, UPDATE_EG | UPDATE_RKS | UPDATE_TLL); +} + +/* set block data (blk : 3bit ) */ +static INLINE void set_block(OPL *opl, int ch, int blk) { + OPL_SLOT *car = CAR(opl, ch); + OPL_SLOT *mod = MOD(opl, ch); + car->blk = blk; + car->blk_fnum = ((blk & 7) << 10) | (car->blk_fnum & 0x3ff); + mod->blk = blk; + mod->blk_fnum = ((blk & 7) << 10) | (mod->blk_fnum & 0x3ff); + request_update(car, UPDATE_EG | UPDATE_RKS | UPDATE_TLL); + request_update(mod, UPDATE_EG | UPDATE_RKS | UPDATE_TLL); +} + +static INLINE void update_rhythm_mode(OPL *opl) { + const uint8_t new_rhythm_mode = (opl->reg[0xbd] >> 5) & 1; + + if (opl->rhythm_mode != new_rhythm_mode) { + if (new_rhythm_mode) { + opl->slot[SLOT_HH].type = 3; + opl->slot[SLOT_HH].pg_keep = 1; + opl->slot[SLOT_SD].type = 3; + opl->slot[SLOT_TOM].type = 3; + opl->slot[SLOT_CYM].type = 3; + opl->slot[SLOT_CYM].pg_keep = 1; + } else { + opl->slot[SLOT_HH].type = 0; + opl->slot[SLOT_HH].pg_keep = 0; + opl->slot[SLOT_SD].type = 1; + opl->slot[SLOT_TOM].type = 0; + opl->slot[SLOT_CYM].type = 1; + opl->slot[SLOT_CYM].pg_keep = 0; + } + } + opl->rhythm_mode = new_rhythm_mode; +} + +static void update_ampm(OPL *opl) { + const uint32_t pm_inc = (opl->test_flag & 8) ? opl->pm_dphase << 10 : opl->pm_dphase; + const uint32_t am_inc = (opl->test_flag & 8) ? 64 : 1; + if (opl->test_flag & 2) { + opl->pm_phase = 0; + opl->am_phase = 0; + } else { + opl->pm_phase = (opl->pm_phase + pm_inc) & (PM_DP_WIDTH - 1); + opl->am_phase += am_inc; + } + opl->lfo_am = am_table[(opl->am_phase >> 6) % sizeof(am_table)] >> (opl->am_mode ? 0 : 2); +} + +static void update_noise(OPL *opl, int cycle) { + int i; + for (i = 0; i < cycle; i++) { + if (opl->noise & 1) { + opl->noise ^= 0x800200; + } + opl->noise >>= 1; + } +} + +static void update_short_noise(OPL *opl) { + const uint32_t pg_hh = opl->slot[SLOT_HH].pg_out; + const uint32_t pg_cym = opl->slot[SLOT_CYM].pg_out; + + const uint8_t h_bit2 = BIT(pg_hh, PG_BITS - 8); + const uint8_t h_bit7 = BIT(pg_hh, PG_BITS - 3); + const uint8_t h_bit3 = BIT(pg_hh, PG_BITS - 7); + + const uint8_t c_bit3 = BIT(pg_cym, PG_BITS - 7); + const uint8_t c_bit5 = BIT(pg_cym, PG_BITS - 5); + + opl->short_noise = (h_bit2 ^ h_bit7) | (h_bit3 ^ c_bit5) | (c_bit3 ^ c_bit5); +} + +static INLINE void calc_phase(OPL_SLOT *slot, int32_t pm_phase, uint8_t pm_mode, uint8_t reset) { + int8_t pm = 0; + if (slot->patch->PM) { + pm = pm_table[(slot->fnum >> 7) & 7][pm_phase >> (PM_DP_BITS - PM_PG_BITS)]; + pm >>= (pm_mode ? 0 : 1); + } + + if (reset) { + slot->pg_phase = 0; + } + slot->pg_phase += (((slot->fnum & 0x3ff) + pm) * ml_table[slot->patch->ML]) << slot->blk >> 1; + slot->pg_phase &= (DP_WIDTH - 1); + slot->pg_out = slot->pg_phase >> DP_BASE_BITS; +} + +static INLINE uint8_t lookup_attack_step(OPL_SLOT *slot, uint32_t counter) { + int index = (counter >> slot->eg_shift) & 7; + switch (slot->eg_rate_h) { + case 13: + return eg_step_tables_fast[slot->eg_rate_l][index]; + case 14: + return eg_step_tables_fast[slot->eg_rate_l][index] << 1; + case 0: + case 15: + return 0; + default: + return eg_step_tables[slot->eg_rate_l][index]; + } +} + +static INLINE uint8_t lookup_decay_step(OPL_SLOT *slot, uint32_t counter) { + int index = (counter >> slot->eg_shift) & 7; + switch (slot->eg_rate_h) { + case 0: + return 0; + case 13: + return eg_step_tables_fast[slot->eg_rate_l][index]; + case 14: + return eg_step_tables_fast[slot->eg_rate_l][index] << 1; + case 15: + return 4; + default: + return eg_step_tables[slot->eg_rate_l][index]; + } +} + +static INLINE void calc_envelope(OPL_SLOT *slot, uint16_t eg_counter, uint8_t test) { + + uint16_t mask = (1 << slot->eg_shift) - 1; + uint8_t s; + + if (slot->eg_state == ATTACK) { + if (0 < slot->eg_out && slot->eg_rate_h > 0 && (eg_counter & mask) == 0) { + s = lookup_attack_step(slot, eg_counter); + slot->eg_out += (~slot->eg_out * s) >> 3; + } + } else { + if (slot->eg_rate_h > 0 && (eg_counter & mask) == 0) { + slot->eg_out = min(EG_MUTE, slot->eg_out + lookup_decay_step(slot, eg_counter)); + } + } + + switch (slot->eg_state) { + case ATTACK: + if (slot->eg_out == 0) { + slot->eg_state = DECAY; + request_update(slot, UPDATE_EG); + } + break; + + case DECAY: + if ((slot->patch->SL != 15) && (slot->eg_out >> 4) == slot->patch->SL) { + slot->eg_state = SUSTAIN; + request_update(slot, UPDATE_EG); + } + break; + + case SUSTAIN: + case RELEASE: + default: + break; + } + + if (test) { + slot->eg_out = 0; + } +} + +static void update_slots(OPL *opl) { + int i; + opl->eg_counter++; + + for (i = 0; i < 18; i++) { + OPL_SLOT *slot = &opl->slot[i]; + if (slot->update_requests) { + commit_slot_update(slot, opl->notesel); + } + calc_envelope(slot, opl->eg_counter, opl->test_flag & 1); + calc_phase(slot, opl->pm_phase, opl->pm_mode, opl->test_flag & 4); + } +} + +/* input: 0..8191 output: -4095..4095 */ +static INLINE int16_t lookup_exp_table(uint16_t i) { + /* from andete's expressoin */ + int16_t t = (exp_table[(i & 0xff) ^ 0xff] + 1024); + int16_t res = t >> ((i & 0x7f00) >> 8); + return (int16_t)(((i & 0x8000) ? ~res : res) * 2); +} + +static INLINE int16_t to_linear(uint16_t h, OPL_SLOT *slot, int16_t am) { + uint16_t att; + if (slot->eg_out >= EG_MAX) + return 0; + + att = min(EG_MUTE, (slot->eg_out + slot->tll + am)) << 3; + return lookup_exp_table(h + att); +} + +static INLINE int16_t calc_slot_car(OPL *opl, int ch, int16_t fm) { + OPL_SLOT *slot = CAR(opl, ch); + + uint8_t am = slot->patch->AM ? opl->lfo_am : 0; + + slot->output[1] = slot->output[0]; + slot->output[0] = to_linear(slot->wave_table[(slot->pg_out + 2 * (fm >> 1)) & (PG_WIDTH - 1)], slot, am); + + return slot->output[0]; +} + +static INLINE int16_t calc_slot_mod(OPL *opl, int ch) { + OPL_SLOT *slot = MOD(opl, ch); + + int16_t fm = slot->patch->FB > 0 ? (slot->output[1] + slot->output[0]) >> (9 - slot->patch->FB) : 0; + uint8_t am = slot->patch->AM ? opl->lfo_am : 0; + + slot->output[1] = slot->output[0]; + slot->output[0] = to_linear(slot->wave_table[(slot->pg_out + fm) & (PG_WIDTH - 1)], slot, am); + + return slot->output[0]; +} + +static INLINE int16_t calc_slot_tom(OPL *opl) { + OPL_SLOT *slot = &(opl->slot[SLOT_TOM]); + + return to_linear(slot->wave_table[slot->pg_out], slot, 0); +} + +/* Specify phase offset directly based on 10-bit (1024-length) sine table */ +#define _PD(phase) ((PG_BITS < 10) ? (phase >> (10 - PG_BITS)) : (phase << (PG_BITS - 10))) + +static INLINE int16_t calc_slot_snare(OPL *opl) { + OPL_SLOT *slot = &(opl->slot[SLOT_SD]); + + uint32_t phase; + + if (BIT(opl->slot[SLOT_HH].pg_out, PG_BITS - 2)) + phase = (opl->noise & 1) ? _PD(0x300) : _PD(0x200); + else + phase = (opl->noise & 1) ? _PD(0x0) : _PD(0x100); + + return to_linear(slot->wave_table[phase], slot, 0); +} + +static INLINE int16_t calc_slot_cym(OPL *opl) { + OPL_SLOT *slot = &(opl->slot[SLOT_CYM]); + + uint32_t phase = opl->short_noise ? _PD(0x300) : _PD(0x100); + + return to_linear(slot->wave_table[phase], slot, 0); +} + +static INLINE int16_t calc_slot_hat(OPL *opl) { + OPL_SLOT *slot = &(opl->slot[SLOT_HH]); + + uint32_t phase; + + if (opl->short_noise) + phase = (opl->noise & 1) ? _PD(0x2d0) : _PD(0x234); + else + phase = (opl->noise & 1) ? _PD(0x34) : _PD(0xd0); + + return to_linear(slot->wave_table[phase], slot, 0); +} + +#define _MO(x) (-(x) >> 1) +#define _RO(x) (x) + +static INLINE int16_t calc_fm(OPL *opl, int ch) { + if (opl->ch_alg[ch]) { + return calc_slot_car(opl, ch, 0) + calc_slot_mod(opl, ch); + } + return calc_slot_car(opl, ch, calc_slot_mod(opl, ch)); +} + +static void latch_timer1(OPL *opl) { opl->timer1_counter = opl->reg[0x02] << 2; } + +static void latch_timer2(OPL *opl) { opl->timer2_counter = opl->reg[0x03] << 4; } + +static void csm_key_on(OPL *opl) { + opl->csm_key_count = 1; + update_key_status(opl); +} + +static void csm_key_off(OPL *opl) { + opl->csm_key_count = 0; + update_key_status(opl); +} + +static void update_timer(OPL *opl) { + if (opl->csm_mode && 0 < opl->csm_key_count) { + csm_key_off(opl); + } + + if (opl->reg[0x04] & 0x01) { + opl->timer1_counter++; + if (opl->timer1_counter >> 10) { + opl->status |= 0x40; // timer1 overflow + if (opl->csm_mode) { + csm_key_on(opl); + } + if (opl->timer1_func) { + opl->timer1_func(opl->timer1_user_data); + } + latch_timer1(opl); + } + } + + if (opl->reg[0x04] & 0x02) { + opl->timer2_counter++; + if (opl->timer2_counter >> 12) { + opl->status |= 0x20; // timer2 overflow + if (opl->timer2_func) { + opl->timer2_func(opl->timer2_user_data); + } + latch_timer2(opl); + } + } +} + +static void update_output(OPL *opl) { + int16_t *out; + int i; + + update_timer(opl); + update_ampm(opl); + update_short_noise(opl); + update_slots(opl); + + out = opl->ch_out; + + /* CH1-6 */ + for (i = 0; i < 6; i++) { + if (!(opl->mask & OPL_MASK_CH(i))) { + out[i] = _MO(calc_fm(opl, i)); + } + } + + /* CH7 */ + if (!opl->rhythm_mode) { + if (!(opl->mask & OPL_MASK_CH(6))) { + out[6] = _MO(calc_fm(opl, 6)); + } + } else { + if (!(opl->mask & OPL_MASK_BD)) { + out[9] = _RO(calc_fm(opl, 6)); + } + } + update_noise(opl, 14); + + /* CH8 */ + if (!opl->rhythm_mode) { + if (!(opl->mask & OPL_MASK_CH(7))) { + out[7] = _MO(calc_fm(opl, 7)); + } + } else { + if (!(opl->mask & OPL_MASK_HH)) { + out[10] = _RO(calc_slot_hat(opl)); + } + if (!(opl->mask & OPL_MASK_SD)) { + out[11] = _RO(calc_slot_snare(opl)); + } + } + update_noise(opl, 2); + + /* CH9 */ + if (!opl->rhythm_mode) { + if (!(opl->mask & OPL_MASK_CH(8))) { + out[8] = _MO(calc_fm(opl, 8)); + } + } else { + if (!(opl->mask & OPL_MASK_TOM)) { + out[12] = _RO(calc_slot_tom(opl)); + } + if (!(opl->mask & OPL_MASK_CYM)) { + out[13] = _RO(calc_slot_cym(opl)); + } + } + update_noise(opl, 2); + + /* ADPCM */ + if (opl->adpcm != NULL && !(opl->mask & OPL_MASK_ADPCM)) { + out[14] = OPL_ADPCM_calc(opl->adpcm); + } +} + +INLINE static void mix_output(OPL *opl) { + int16_t out = 0; + int i; + for (i = 0; i < 15; i++) { + out += opl->ch_out[i]; + } + if (opl->conv) { + OPL_RateConv_putData(opl->conv, 0, out); + } else { + opl->mix_out[0] = out; + } +} + +INLINE static void mix_output_stereo(OPL *opl) { + int16_t *out = opl->mix_out; + int i; + out[0] = out[1] = 0; + for (i = 0; i < 15; i++) { + if (opl->pan[i] & 2) + out[0] += (int16_t)(opl->ch_out[i] * opl->pan_fine[i][0] / 4096); + if (opl->pan[i] & 1) + out[1] += (int16_t)(opl->ch_out[i] * opl->pan_fine[i][1] / 4096); + } + if (opl->conv) { + OPL_RateConv_putData(opl->conv, 0, out[0]); + OPL_RateConv_putData(opl->conv, 1, out[1]); + } +} + +/*********************************************************** + + External Interfaces + +***********************************************************/ + +OPL *OPL_new(uint32_t clk, uint32_t rate) { + OPL *opl; + + if (!table_initialized) { + initializeTables(); + } + + opl = (OPL *)calloc(1, sizeof(OPL)); + if (opl == NULL) + return NULL; + + opl->adpcm = NULL; + opl->clk = clk; + opl->rate = rate; + opl->mask = 0; + opl->conv = NULL; + opl->mix_out[0] = 0; + opl->mix_out[1] = 0; + opl->timer1_func = NULL; + opl->timer1_user_data = NULL; + opl->timer2_func = NULL; + opl->timer2_user_data = NULL; + + OPL_reset(opl); + + return opl; +} + +void OPL_delete(OPL *opl) { + if (opl->conv) { + OPL_RateConv_delete(opl->conv); + opl->conv = NULL; + } + if (opl->adpcm) { + OPL_ADPCM_delete(opl->adpcm); + opl->adpcm = NULL; + } + free(opl); +} + +static void reset_rate_conversion_params(OPL *opl) { + const double f_out = opl->rate; + const double f_inp = opl->clk / 72.0; + + opl->out_time = 0; + opl->out_step = opl->clk; + opl->inp_step = opl->rate * 72; + /* the largest inp_shift such that inp_recip fits in 32 bits */ + opl->inp_shift = 32; + while ((((uint64_t)1 << (opl->inp_shift + 1)) - 1) / opl->inp_step < 0xffffffff) { + opl->inp_shift++; + } + opl->inp_recip = (uint32_t)((((uint64_t)1 << opl->inp_shift) - 1) / opl->inp_step + 1); + + if (opl->conv) { + OPL_RateConv_delete(opl->conv); + opl->conv = NULL; + } + + if (floor(f_inp) != f_out && floor(f_inp + 0.5) != f_out) { + opl->conv = OPL_RateConv_new(f_inp, f_out, 2); + } + + if (opl->conv) { + OPL_RateConv_reset(opl->conv); + } +} + +static void refresh_adpcm_object(OPL *opl) { + if (opl->chip_type == TYPE_Y8950) { + if (opl->adpcm == NULL) { + opl->adpcm = OPL_ADPCM_new(opl->clk); + } + } else { + if (opl->adpcm != NULL) { + OPL_ADPCM_delete(opl->adpcm); + opl->adpcm = NULL; + } + } + if (opl->adpcm != NULL) { + OPL_ADPCM_reset(opl->adpcm); + } +} + +void OPL_reset(OPL *opl) { + int i; + + if (!opl) + return; + + opl->adr = 0; + + opl->csm_mode = 0; + opl->csm_key_count = 0; + opl->notesel = 0; + + opl->status = 0; + opl->timer1_counter = 0; + opl->timer2_counter = 0; + + opl->pm_phase = 0; + opl->am_phase = 0; + + opl->noise = 1; + opl->short_noise = 0; + opl->mask = 0; + + opl->test_flag = 0; + opl->lfo_am = 0; + + opl->rhythm_mode = 0; + opl->slot_key_status = 0; + opl->eg_counter = 0; + + opl->mix_out[0] = 0; + opl->mix_out[1] = 0; + + reset_rate_conversion_params(opl); + + for (i = 0; i < 18; i++) { + reset_slot(&opl->slot[i], i); + } + + for (i = 0; i < 9; i++) { + opl->ch_alg[i] = 0; + } + + for (i = 0; i < 0x100; i++) { + opl->reg[i] = 0; + } + opl->reg[0x04] = 0x18; // MASK_EOS | MASK_BUF_RDY + + opl->pm_dphase = PM_DP_WIDTH / (1024 * 8); + + for (i = 0; i < 15; i++) { + opl->pan[i] = 3; + opl->pan_fine[i][1] = opl->pan_fine[i][0] = 4096; + } + + for (i = 0; i < 15; i++) { + opl->ch_out[i] = 0; + } + + refresh_adpcm_object(opl); +} + +void OPL_setRate(OPL *opl, uint32_t rate) { + opl->rate = rate; + reset_rate_conversion_params(opl); +} + +void OPL_setQuality(OPL *opl, uint8_t q) {} + +void OPL_setChipType(OPL *opl, uint8_t type) { + if (type < TYPE_MAX) { + opl->chip_type = type; + refresh_adpcm_object(opl); + } +} + +void OPL_writeIO(OPL *opl, uint32_t adr, uint8_t val) { + if (adr & 1) + OPL_writeReg(opl, opl->adr, val); + else + opl->adr = val; +} + +void OPL_setPan(OPL *opl, uint32_t ch, uint8_t pan) { opl->pan[ch & 15] = pan; } + +void OPL_setPanFine(OPL *opl, uint32_t ch, float pan[2]) { + opl->pan_fine[ch & 15][0] = (int32_t)floor(pan[0] * 4096.0 + 0.5); + opl->pan_fine[ch & 15][1] = (int32_t)floor(pan[1] * 4096.0 + 0.5); +} + +/* output phase of the rate converter: round(dn * SINC_RESO), where dn = (inp_step - out_time) / inp_step + (or 0 if out_time is 0) is the position of the output sample between the last two input samples. + It is derived from out_time every time, so that it never drifts. */ +static INLINE uint32_t get_conv_phase(OPL *opl) { + uint32_t d = opl->out_time ? opl->inp_step - opl->out_time : 0; + /* dn in 0.32 fixed point */ + uint32_t dn = (uint32_t)(((uint64_t)d * opl->inp_recip) >> (opl->inp_shift - 32)); + return (uint32_t)(((uint64_t)dn + (1u << (31 - SINC_RESO_BITS))) >> (32 - SINC_RESO_BITS)); +} + +int16_t OPL_calc(OPL *opl) { + while (opl->out_step > opl->out_time) { + opl->out_time += opl->inp_step; + update_output(opl); + mix_output(opl); + } + opl->out_time -= opl->out_step; + if (opl->conv) { + opl->mix_out[0] = rateconv_get(opl->conv, 0, get_conv_phase(opl)); + } + return opl->mix_out[0]; +} + +void OPL_calcStereo(OPL *opl, int32_t out[2]) { + while (opl->out_step > opl->out_time) { + opl->out_time += opl->inp_step; + update_output(opl); + mix_output_stereo(opl); + } + opl->out_time -= opl->out_step; + if (opl->conv) { + uint32_t p = get_conv_phase(opl); + out[0] = rateconv_get(opl->conv, 0, p); + out[1] = rateconv_get(opl->conv, 1, p); + } else { + out[0] = opl->mix_out[0]; + out[1] = opl->mix_out[1]; + } +} + +uint32_t OPL_setMask(OPL *opl, uint32_t mask) { + uint32_t ret; + + if (opl) { + ret = opl->mask; + opl->mask = mask; + return ret; + } else + return 0; +} + +uint32_t OPL_toggleMask(OPL *opl, uint32_t mask) { + uint32_t ret; + + if (opl) { + ret = opl->mask; + opl->mask ^= mask; + return ret; + } else + return 0; +} + +void OPL_writeReg(OPL *opl, uint32_t reg, uint8_t data) { + + int32_t s, c; + + static int32_t stbl[32] = {0, 2, 4, 1, 3, 5, -1, -1, 6, 8, 10, 7, 9, 11, -1, -1, + 12, 14, 16, 13, 15, 17, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; + + reg = reg & 0xff; + + if ((reg == 0x04) && (data & 0x80)) { + // IRQ RESET + opl->status = 0; + opl->reg[0x04] &= 0x7f; + if (opl->adpcm) { + OPL_ADPCM_resetStatus(opl->adpcm); + } + return; + } + + opl->reg[reg] = data; + + if (reg == 0x01) { + + opl->test_flag = data; + + } else if (reg == 0x04) { + + if (data & 0x01) { + latch_timer1(opl); + } + if (data & 0x02) { + latch_timer2(opl); + } + + } else if (0x07 <= reg && reg <= 0x12) { + + if (reg == 0x08) { + opl->csm_mode = (data >> 7) & 1; + opl->notesel = (data >> 6) & 1; + } + + if (opl->adpcm != NULL && opl->chip_type == TYPE_Y8950) { + OPL_ADPCM_writeReg(opl->adpcm, reg, data); + } + + } else if (0x20 <= reg && reg < 0x40) { + + s = stbl[reg - 0x20]; + if (s >= 0) { + opl->slot[s].patch->AM = (data >> 7) & 1; + opl->slot[s].patch->PM = (data >> 6) & 1; + opl->slot[s].patch->EG = (data >> 5) & 1; + opl->slot[s].patch->KR = (data >> 4) & 1; + opl->slot[s].patch->ML = (data) & 15; + request_update(&(opl->slot[s]), UPDATE_ALL); + } + + } else if (0x40 <= reg && reg < 0x60) { + + s = stbl[reg - 0x40]; + if (s >= 0) { + opl->slot[s].patch->KL = (data >> 6) & 3; + opl->slot[s].patch->TL = (data) & 63; + request_update(&(opl->slot[s]), UPDATE_ALL); + } + + } else if (0x60 <= reg && reg < 0x80) { + + s = stbl[reg - 0x60]; + if (s >= 0) { + opl->slot[s].patch->AR = (data >> 4) & 15; + opl->slot[s].patch->DR = (data) & 15; + request_update(&(opl->slot[s]), UPDATE_EG); + } + + } else if (0x80 <= reg && reg < 0xa0) { + + s = stbl[reg - 0x80]; + if (s >= 0) { + opl->slot[s].patch->SL = (data >> 4) & 15; + opl->slot[s].patch->RR = (data) & 15; + request_update(&(opl->slot[s]), UPDATE_EG); + } + + } else if (0xa0 <= reg && reg < 0xa9) { + + c = reg - 0xa0; + set_fnumber(opl, c, data + ((opl->reg[reg + 0x10] & 3) << 8)); + + } else if (0xb0 <= reg && reg < 0xb9) { + + c = reg - 0xb0; + set_fnumber(opl, c, ((data & 3) << 8) + opl->reg[reg - 0x10]); + set_block(opl, c, (data >> 2) & 7); + update_key_status(opl); + + } else if (0xc0 <= reg && reg < 0xc9) { + + c = reg - 0xc0; + opl->slot[c * 2].patch->FB = (data >> 1) & 7; + opl->ch_alg[c] = data & 1; + + } else if (reg == 0xbd) { + + update_rhythm_mode(opl); + update_key_status(opl); + opl->am_mode = (data >> 7) & 1; + opl->pm_mode = (data >> 6) & 1; + + } else if (0xe0 <= reg && reg < 0x100) { + if (opl->chip_type == TYPE_YM3812 && (opl->reg[0x01] & 0x20)) { + s = stbl[reg - 0xe0]; + if (s >= 0) { + opl->slot[s].patch->WS = data & 3; + request_update(&(opl->slot[s]), UPDATE_WS); + } + } + } +} + +uint8_t OPL_readIO(OPL *opl) { return opl->reg[opl->adr]; } + +uint8_t OPL_status(OPL *opl) { + uint8_t status = opl->status; + + if (opl->adpcm) { + status |= OPL_ADPCM_status(opl->adpcm); + } + + status &= ~(opl->reg[0x04] & 0x78); // IRQ MASK + + if (status & 0x78) { + return status | 0x80; // IRQ=1 + } + return status & 0x7f; // IRQ = 0 +} + +void OPL_writeADPCMData(OPL *opl, uint8_t type, uint32_t start, uint32_t length, const uint8_t *data) { + if (opl->adpcm != NULL) { + if (type == 0) { + OPL_ADPCM_writeRAM(opl->adpcm, start, length, data); + } else { + OPL_ADPCM_writeROM(opl->adpcm, start, length, data); + } + } +} + +int OPL_save_state(OPL *opl, uint8_t *out) { + int n = (int)sizeof(OPL); + if (out) + memcpy(out, opl, sizeof(OPL)); + /* The ADPCM engine (Y8950) is a separately malloc'd object, so its dynamic + * state lives outside sizeof(OPL); append it. Its RAM/ROM sample buffers are + * not included (loaded once, constant). */ + if (opl->adpcm != NULL) + n += OPL_ADPCM_save_state(opl->adpcm, out ? out + n : (uint8_t *)0); + return n; +} + +void OPL_load_state(OPL *opl, const uint8_t *in, int size) { + /* Preserve THIS instance's own allocations / host bindings across the struct + * copy, so the blob carries no source-instance pointers. This makes the state + * position-independent: it can be restored into a DIFFERENT OPL instance + * (cross-instance copy), not only the one that produced it. */ + OPL_ADPCM *adpcm = opl->adpcm; + OPL_RateConv *conv = opl->conv; + void *t1u = opl->timer1_user_data, *t2u = opl->timer2_user_data; + void (*t1f)(void *) = opl->timer1_func; + void (*t2f)(void *) = opl->timer2_func; + int i; + memcpy(opl, in, sizeof(OPL)); + opl->adpcm = adpcm; + opl->conv = conv; + /* reset SRC: its ring is stale after a load. Its phase is derived from out_time, so needs no re-alignment. */ + if (opl->conv) OPL_RateConv_reset(opl->conv); + opl->timer1_user_data = t1u; + opl->timer2_user_data = t2u; + opl->timer1_func = t1f; + opl->timer2_func = t2f; + /* each slot's `patch` aliases its own embedded __patch; wave_table points to a + * static table (stable address across instances) so it needs no relink. */ + for (i = 0; i < 18; i++) + opl->slot[i].patch = &(opl->slot[i].__patch); + if (opl->adpcm != NULL) + OPL_ADPCM_load_state(opl->adpcm, in + sizeof(OPL), size - (int)sizeof(OPL)); +} \ No newline at end of file diff --git a/third_party/emu8950/emu8950.h b/third_party/emu8950/emu8950.h new file mode 100644 index 00000000..361d6a31 --- /dev/null +++ b/third_party/emu8950/emu8950.h @@ -0,0 +1,262 @@ +#ifndef _EMU8950_H_ +#define _EMU8950_H_ + +#include "emuadpcm.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define OPL_DEBUG 0 + +/* voice data */ +typedef struct __OPL_PATCH { + uint8_t TL, FB, EG, ML, AR, DR, SL, RR, KR, KL, AM, PM, WS; +} OPL_PATCH; + +/* mask */ +#define OPL_MASK_CH(x) (1 << (x)) +#define OPL_MASK_HH (1 << 9) +#define OPL_MASK_CYM (1 << 10) +#define OPL_MASK_TOM (1 << 11) +#define OPL_MASK_SD (1 << 12) +#define OPL_MASK_BD (1 << 13) +#define OPL_MASK_ADPCM (1 << 14) +#define OPL_MASK_RHYTHM (OPL_MASK_HH | OPL_MASK_CYM | OPL_MASK_TOM | OPL_MASK_SD | OPL_MASK_BD) + +/* rate conveter */ +typedef struct __OPL_RateConv { + int ch; + uint32_t timer; /* fractional phase of the output in 0.32 fixed point */ + uint32_t timer_step; /* fractional part of f_ratio in 0.32 fixed point */ + double f_ratio; + int16_t *sinc_table; + int16_t **buf; /* ring buffer of LW samples per channel, stored twice so that the latest LW samples are contiguous */ + int *pos; +} OPL_RateConv; + +OPL_RateConv *OPL_RateConv_new(double f_inp, double f_out, int ch); +void OPL_RateConv_reset(OPL_RateConv *conv); +void OPL_RateConv_putData(OPL_RateConv *conv, int ch, int16_t data); +int16_t OPL_RateConv_getData(OPL_RateConv *conv, int ch); +void OPL_RateConv_delete(OPL_RateConv *conv); + +/* slot */ +typedef struct __OPL_SLOT { + uint8_t number; + + /* type flags: + * 000000SM + * |+-- M: 0:modulator 1:carrier + * +--- S: 0:normal 1:single slot mode (sd, tom, hh or cym) + */ + uint8_t type; + + OPL_PATCH __patch; + OPL_PATCH *patch; /* = alias for __patch */ + + /* slot output */ + int32_t output[2]; /* output value, latest and previous. */ + + /* phase generator (pg) */ + uint16_t *wave_table; /* wave table */ + uint32_t pg_phase; /* pg phase */ + uint32_t pg_out; /* pg output, as index of wave table */ + uint8_t pg_keep; /* if 1, pg_phase is preserved when key-on */ + uint16_t blk_fnum; /* (block << 9) | f-number */ + uint16_t fnum; /* f-number (9 bits) */ + uint8_t blk; /* block (3 bits) */ + + /* envelope generator (eg) */ + uint8_t eg_state; /* current state */ + uint16_t tll; /* total level + key scale level*/ + uint8_t rks; /* key scale offset (rks) for eg speed */ + uint8_t eg_rate_h; /* eg speed rate high 4bits */ + uint8_t eg_rate_l; /* eg speed rate low 2bits */ + uint32_t eg_shift; /* shift for eg global counter, controls envelope speed */ + int16_t eg_out; /* eg output */ + + uint32_t update_requests; /* flags to debounce update */ + +#if OPL_DEBUG + uint8_t last_eg_state; +#endif +} OPL_SLOT; + +typedef struct __OPL { + OPL_ADPCM *adpcm; + uint32_t clk; + uint32_t rate; + + uint8_t chip_type; + + uint32_t adr; + + uint8_t csm_mode; + uint8_t csm_key_count; + uint8_t notesel; + + /* in units of 1/(clk * rate) sec, so that all steps are integers */ + uint32_t inp_step; + uint32_t out_step; + uint32_t out_time; + /* inp_recip = ceil(2^inp_shift / inp_step), to get the rate converter phase without division */ + uint32_t inp_recip; + uint32_t inp_shift; + + uint8_t reg[0x100]; + uint8_t test_flag; + uint32_t slot_key_status; + uint8_t rhythm_mode; + + uint32_t eg_counter; + + uint32_t pm_phase; + uint32_t pm_dphase; + + int32_t am_phase; + int32_t am_dphase; + uint8_t lfo_am; + + uint32_t noise; + uint8_t short_noise; + + OPL_SLOT slot[18]; + uint8_t ch_alg[9]; // alg for each channels + + uint8_t pan[16]; + int32_t pan_fine[16][2]; /* 4.12 fixed point */ + + uint32_t mask; + uint8_t am_mode; + uint8_t pm_mode; + + /* channel output */ + /* 0..8:tone 9:bd 10:hh 11:sd 12:tom 13:cym 14:adpcm */ + int16_t ch_out[15]; + + int16_t mix_out[2]; + + OPL_RateConv *conv; + + uint32_t timer1_counter; // 80us counter + uint32_t timer2_counter; // 320us counter + void *timer1_user_data; + void *timer2_user_data; + void (*timer1_func)(void *user); + void (*timer2_func)(void *user); + uint8_t status; + +} OPL; + +OPL *OPL_new(uint32_t clk, uint32_t rate); +void OPL_delete(OPL *); + +void OPL_reset(OPL *); + +/** + * Set output wave sampling rate. + * @param rate sampling rate. If clock / 72 (typically 49716 or 49715 at 3.58MHz) is set, the internal rate converter is disabled. + */ +void OPL_setRate(OPL *opl, uint32_t rate); + +/** + * Set internal calcuration quality. Currently no effects, just for compatibility. + * >= v1.0.0 always synthesizes internal output at clock/72 Hz. + */ +void OPL_setQuality(OPL *opl, uint8_t q); + +/** + * Set OPL chip type. + * @param type 0:Y8950, 1:YM3526, 2:YM3812 + */ +void OPL_setChipType(OPL *opl, uint8_t type); + +/** + * Set pan pot (extra function - not YM2413 chip feature) + * @param ch 0..8:tone 9:bd 10:hh 11:sd 12:tom 13:cym 14,15:reserved + * @param pan 0:mute 1:right 2:left 3:center + * ``` + * pan: 76543210 + * |+- bit 1: enable Left output + * +-- bit 0: enable Right output + * ``` + */ +void OPL_setPan(OPL *opl, uint32_t ch, uint8_t pan); + +/** + * Set fine-grained panning + * @param ch 0..8:tone 9:bd 10:hh 11:sd 12:tom 13:cym 14,15:reserved + * @param pan output strength of left/right channel. + * pan[0]: left, pan[1]: right. pan[0]=pan[1]=1.0f for center. + */ +void OPL_setPanFine(OPL *opl, uint32_t ch, float pan[2]); + +void OPL_writeIO(OPL *opl, uint32_t reg, uint8_t val); +void OPL_writeReg(OPL *opl, uint32_t reg, uint8_t val); + +/** + * Calculate sample + */ +int16_t OPL_calc(OPL *opl); + +/** + * Calulate stereo sample + */ +void OPL_calcStereo(OPL *opl, int32_t out[2]); + +/** + * Set channel mask + * @param mask mask flag: OPL_MASK_* can be used. + * - bit 0..8: mask for ch 1 to 9 (OPL_MASK_CH(i)) + * - bit 9: mask for Hi-Hat (OPL_MASK_HH) + * - bit 10: mask for Top-Cym (OPL_MASK_CYM) + * - bit 11: mask for Tom (OPL_MASK_TOM) + * - bit 12: mask for Snare Drum (OPL_MASK_SD) + * - bit 13: mask for Bass Drum (OPL_MASK_BD) + */ +uint32_t OPL_setMask(OPL *, uint32_t mask); + +/** + * Toggler channel mask flag + */ +uint32_t OPL_toggleMask(OPL *, uint32_t mask); + +uint8_t OPL_readIO(OPL *opl); + +/** + * Read OPL status register + * @returns + * 76543210 + * ||||| +- D0: PCM/BSY + * ||||+---- D3: BUF/RDY + * |||+----- D4: EOS + * ||+------ D5: TIMER2 + * |+------- D6: TIMER1 + * +-------- D7: IRQ + */ +uint8_t OPL_status(OPL *opl); + +void OPL_writeADPCMData(OPL *opl, uint8_t type, uint32_t start, uint32_t length, const uint8_t *data); + +/* Save/restore the emulator state. Serialises the OPL core plus the Y8950 ADPCM + * engine state (a separately malloc'd object). The 256K ADPCM RAM/ROM buffers + * are NOT included — they are treated as constant sample data loaded once. A + * load keeps this instance's live RAM/ROM (and conv) allocations. out=NULL + * returns the required size. */ +int OPL_save_state(OPL *opl, uint8_t *out); +void OPL_load_state(OPL *opl, const uint8_t *in, int size); + +/* for compatibility */ +#define OPL_set_rate OPL_setRate +#define OPL_set_quality OPL_setQuality +#define OPL_set_pan OPL_setPan +#define OPL_set_pan_fine OPL_setPanFine +#define OPL_calc_stereo OPL_calcStereo + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/third_party/emu8950/emuadpcm.c b/third_party/emu8950/emuadpcm.c new file mode 100644 index 00000000..567b1b41 --- /dev/null +++ b/third_party/emu8950/emuadpcm.c @@ -0,0 +1,316 @@ +/** + * ADPCM for Y8950 + */ +#include "emuadpcm.h" +#include +#include +#include + +#define DMAX 0x5FFF +#define DMIN 0x7F +#define DDEF 0x7F + +#define DECODE_MAX 32767 +#define DECODE_MIN (-32768) + +#define CLAP(min, x, max) ((x < min) ? min : (max < x) ? max : x) + +/* Bitmask for register $07 */ +#define R07_RESET 1 +#define R07_SP_OFF 8 +#define R07_REPEAT 16 +#define R07_MEMORY_DATA 32 +#define R07_REC 64 +#define R07_START 128 + +/* Bitmask for register $08 */ +#define R08_ROM 1 +#define R08_64K 2 +#define R08_DA_AD 4 +#define R08_SAMPL 8 +#define R08_NOTE_SET 64 +#define R08_CSM 128 + +/* Bit for status register */ +#define STATUS_PCM_BSY 1 +#define STATUS_BUF_RDY 8 +#define STATUS_EOS 16 + +#define RAM_SIZE (256 * 1024) +#define ROM_SIZE (256 * 1024) + +OPL_ADPCM *OPL_ADPCM_new(uint32_t clk) { + OPL_ADPCM *_this; + + _this = (OPL_ADPCM *)calloc(1, sizeof(OPL_ADPCM)); + if (!_this) + return NULL; + + _this->clk = clk; + + /* 256Kbytes RAM */ + _this->memory[0] = (uint8_t *)malloc(RAM_SIZE); + if (!_this->memory[0]) + goto Error_Exit; + memset(_this->memory[0], 0, RAM_SIZE); + + /* 256Kbytes ROM */ + _this->memory[1] = (uint8_t *)malloc(ROM_SIZE); + if (!_this->memory[1]) + goto Error_Exit; + memset(_this->memory[1], 0, ROM_SIZE); + + OPL_ADPCM_reset(_this); + + return _this; + +Error_Exit: + OPL_ADPCM_delete(_this); + return NULL; +} + +void OPL_ADPCM_delete(OPL_ADPCM *_this) { + if (_this) { + free(_this->memory[0]); + free(_this->memory[1]); + free(_this); + } +} + +void OPL_ADPCM_reset(OPL_ADPCM *_this) { + int i; + + for (i = 0; i < 0x20; i++) + _this->reg[i] = 0; + + _this->play_start = 0; + _this->status = 0; + _this->play_addr = 0; + _this->start_addr = 0; + _this->stop_addr = 0; + _this->delta_addr = 0; + _this->delta_n = 0; + _this->wave = _this->memory[0]; + _this->play_addr_mask = _this->reg[0x08] & R08_64K ? (1 << 17) - 1 : (1 << 19) - 1; + _this->output[0] = _this->output[1] = 0; +} + +int OPL_ADPCM_save_state(OPL_ADPCM *_this, uint8_t *out) { + /* Engine state only; the 256K RAM/ROM sample buffers are loaded once and not + * part of the snapshot (see OPL_ADPCM_load_state, which keeps this instance's). */ + if (out) + memcpy(out, _this, sizeof(OPL_ADPCM)); + return (int)sizeof(OPL_ADPCM); +} + +void OPL_ADPCM_load_state(OPL_ADPCM *_this, const uint8_t *in, int size) { + if (size < (int)sizeof(OPL_ADPCM)) + return; + /* keep this instance's own RAM/ROM buffers across the copy */ + uint8_t *ram = _this->memory[0]; + uint8_t *rom = _this->memory[1]; + memcpy(_this, in, sizeof(OPL_ADPCM)); + _this->memory[0] = ram; + _this->memory[1] = rom; + /* `wave` is the RAM/ROM base selected by reg 0x08 — re-point at this instance's + * buffers so a snapshot restored into a different instance is valid. */ + _this->wave = (_this->reg[0x08] & R08_ROM) ? _this->memory[1] : _this->memory[0]; +} + +#define DELTA_ADDR_MAX (1 << 16) +#define DELTA_ADDR_MASK (DELTA_ADDR_MAX - 1) + +/* Update OPL_ADPCM data stage (Register $0F) */ +static inline int update_stage(OPL_ADPCM *_this) { + _this->delta_addr += _this->delta_n; + + if (_this->delta_addr & DELTA_ADDR_MAX) { + _this->delta_addr &= DELTA_ADDR_MASK; + _this->play_addr = (_this->play_addr + 1) & (_this->play_addr_mask); + + if (_this->play_addr == (_this->stop_addr & _this->play_addr_mask)) { + if (_this->reg[0x07] & R07_REPEAT) { + _this->play_addr = _this->start_addr & (_this->play_addr_mask); + } else { + _this->play_start = 0; + _this->status &= ~STATUS_PCM_BSY; + _this->status |= STATUS_EOS; + } + } else { + _this->reg[0x0F] = _this->wave[_this->play_addr >> 1]; + } + + return 1; + } + + return 0; +} + +static inline void update_output(OPL_ADPCM *_this, uint32_t val) { + static uint32_t F[] = { + 57, 57, 57, 57, 77, 102, 128, 153 // This table values are from ymdelta.c by Tatsuyuki Satoh. + }; + + _this->output[1] = _this->output[0]; + + if (val & 8) + _this->output[0] -= (_this->diff * ((val & 7) * 2 + 1)) >> 3; + else + _this->output[0] += (_this->diff * ((val & 7) * 2 + 1)) >> 3; + + _this->output[0] = CLAP(DECODE_MIN, _this->output[0], DECODE_MAX); + _this->diff = CLAP(DMIN, (_this->diff * F[val & 7]) >> 6, DMAX); +} + +static inline uint32_t calc(OPL_ADPCM *_this) { + uint32_t val; + + if (_this->play_start && update_stage(_this)) { + if (_this->play_addr & 1) + val = _this->reg[0x0F] & 0x0F; + else + val = _this->reg[0x0F] >> 4; + + update_output(_this, val); + } + + return ((_this->output[0] + _this->output[1]) * (_this->reg[0x12] & 0xff)) >> 13; +} + +int16_t OPL_ADPCM_calc(OPL_ADPCM *_this) { + if (_this->reg[0x07] & R07_SP_OFF) + return 0; + + if (!_this->play_start) + return 0; + + return calc(_this); +} + +/* mode= 0:RAM256k 1:ROM 2:RAM64k */ +static uint32_t decode_start_address(uint8_t mode, uint8_t l, uint8_t h) { + switch (mode) { + case 0: + return ((h << 8) | l) << 2; + default: + return ((h << 8) | l) << 5; + } +} + +static uint32_t decode_stop_address(uint8_t mode, uint8_t l, uint8_t h) { + switch (mode) { + case 0: + return (((h << 8) | l) << 2) | 3; + default: + return (((h << 8) | l) << 5) | 31; + } +} + +void OPL_ADPCM_writeReg(OPL_ADPCM *_this, uint32_t adr, uint32_t data) { + adr &= 0x1f; + data &= 0xff; + + switch (adr) { + case 0x07: /* START/REC/MEM DATA/REPEAT/SP-OFF/RESET */ + if (data & R07_RESET) { + _this->play_start = 0; + break; + } + if (data & R07_START) { + _this->play_start = 1; + _this->play_addr = _this->start_addr & _this->play_addr_mask; + _this->delta_addr = 0; + _this->output[0] = 0; + _this->output[1] = 0; + _this->diff = DDEF; + _this->status |= STATUS_PCM_BSY; + } else { + _this->play_start = 0; + } + _this->reg[0x07] = data; + break; + + case 0x08: /* CSM/KEY BOARD SPLIT/SAMPLE/DA AD/64K/ROM */ + _this->reg[0x08] = data; + _this->wave = _this->reg[0x08] & R08_ROM ? _this->memory[1] : _this->memory[0]; + _this->play_addr_mask = _this->reg[0x08] & R08_64K ? (1 << 17) - 1 : (1 << 19) - 1; + break; + + case 0x09: /* START ADDRESS (L) */ + case 0x0A: /* START ADDRESS (H) */ + _this->reg[adr] = data; + _this->start_addr = decode_start_address(_this->reg[0x08] & 3, _this->reg[0x09], _this->reg[0x0A]) << 1; + break; + + case 0x0B: /* STOP ADDRESS (L) */ + case 0x0C: /* STOP ADDRESS (H) */ + _this->reg[adr] = data; + _this->stop_addr = decode_stop_address(_this->reg[0x08] & 3, _this->reg[0x0B], _this->reg[0x0C]) << 1; + break; + + case 0x0D: /* PRESCALE (L) */ + _this->reg[0x0D] = data; + break; + + case 0x0E: /* PRESCALE (H) */ + _this->reg[0x0E] = data; + break; + + case 0x0F: /* OPL_ADPCM-DATA */ + _this->reg[0x0F] = data; + + if ((_this->reg[0x07] & R07_REC) && (_this->reg[0x07] & R07_MEMORY_DATA)) { + _this->wave[_this->play_addr >> 1] = data; + _this->play_addr = (_this->play_addr + 2) & (_this->play_addr_mask); + if (_this->play_addr >= (_this->stop_addr & _this->play_addr_mask)) { + //_this->status |= STATUS_EOS; /* Bug? */ + } + } + break; + + case 0x10: /* DELTA-N (L) */ + case 0x11: /* DELTA-N (H) */ + _this->reg[adr] = data; + _this->delta_n = (_this->reg[0x11] << 8) | _this->reg[0x10]; + break; + + case 0x12: /* ENVELOP CONTROL */ + _this->reg[0x12] = data; + break; + + default: + break; + } +} + +/** + * 76543210 + * || +- D0: PCM-BSY + * |+---- D3: BUF-RDY + * +----- D4: EOS + * IRQ bit (D7) is not implemented on this module. + */ +uint8_t OPL_ADPCM_status(OPL_ADPCM *_this) { + // BUF_RDY is always 1 - it is not accurate but practically okay. + return _this->status | STATUS_BUF_RDY; +} + +void OPL_ADPCM_resetStatus(OPL_ADPCM *_this) { + _this->status = 0; +} + +void OPL_ADPCM_writeRAM(OPL_ADPCM *_this, uint32_t start, uint32_t length, const uint8_t *data) { + if (start >= RAM_SIZE) return; + if (start + length > RAM_SIZE) { + length = RAM_SIZE - start; + } + memcpy(_this->memory[0] + start, data, length); +} + +void OPL_ADPCM_writeROM(OPL_ADPCM *_this, uint32_t start, uint32_t length, const uint8_t *data) { + if (start >= ROM_SIZE) return; + if (start + length > ROM_SIZE) { + length = ROM_SIZE - start; + } + memcpy(_this->memory[1] + start, data, length); +} \ No newline at end of file diff --git a/third_party/emu8950/emuadpcm.h b/third_party/emu8950/emuadpcm.h new file mode 100644 index 00000000..a1782816 --- /dev/null +++ b/third_party/emu8950/emuadpcm.h @@ -0,0 +1,43 @@ +#ifndef _EMUADPCM_H_ +#define _EMUADPCM_H_ + +#include + +typedef struct __OPL_ADPCM { + uint32_t clk; + + uint8_t reg[0x20]; + + uint8_t *wave; /* ADPCM DATA */ + uint8_t *memory[2]; /* [0] RAM, [1] ROM */ + + uint8_t status; + + uint32_t start_addr; + uint32_t stop_addr; + uint32_t play_addr; /* Current play address * 2 */ + uint32_t delta_addr; /* 16bit address */ + uint32_t delta_n; + uint32_t play_addr_mask; + + uint8_t play_start; + + int32_t output[2]; + uint32_t diff; + +} OPL_ADPCM; + +OPL_ADPCM *OPL_ADPCM_new(uint32_t clk); +void OPL_ADPCM_reset(OPL_ADPCM *); +void OPL_ADPCM_delete(OPL_ADPCM *); +void OPL_ADPCM_writeReg(OPL_ADPCM *, uint32_t reg, uint32_t val); +int16_t OPL_ADPCM_calc(OPL_ADPCM *); +uint8_t OPL_ADPCM_status(OPL_ADPCM *); +void OPL_ADPCM_resetStatus(OPL_ADPCM *); +void OPL_ADPCM_writeRAM(OPL_ADPCM *, uint32_t start, uint32_t length, const uint8_t *data); +void OPL_ADPCM_writeROM(OPL_ADPCM *, uint32_t start, uint32_t length, const uint8_t *data); +/* Save/restore state (engine only; the RAM/ROM sample buffers are kept, not + * copied, so the state can be restored into a different instance). out=NULL -> size. */ +int OPL_ADPCM_save_state(OPL_ADPCM *, uint8_t *out); +void OPL_ADPCM_load_state(OPL_ADPCM *, const uint8_t *in, int size); +#endif diff --git a/tools/ci_build_app.sh b/tools/ci_build_app.sh new file mode 100755 index 00000000..21958be7 --- /dev/null +++ b/tools/ci_build_app.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +SDL_SDK="${SDL_SDK:-$ROOT/../cart/vendor/SDL}" +CC_BIN="${CC:-gcc}" +OUT="${1:-$ROOT/build/cart-sdl/linux/wolf3d-revive}" + +if [[ ! -f "$SDL_SDK/build/libSDL3.a" ]]; then + echo "FAIL: SDL static library not found: $SDL_SDK/build/libSDL3.a" >&2 + exit 2 +fi +if ! command -v "$CC_BIN" >/dev/null 2>&1; then + echo "FAIL: compiler not found: $CC_BIN" >&2 + exit 2 +fi + +mkdir -p "$(dirname "$OUT")" + +# Flags mirror cart.toml [linux] + cart-sdl static SDL profile. +srcs=() +while IFS= read -r f; do srcs+=("$f"); done < <(find "$ROOT/src" -name '*.c' | sort) + +echo "START build app -> $OUT" >&2 +"$CC_BIN" -std=c11 -O2 -Wall -Wextra -Wpedantic -Wconversion -Wshadow \ + -I"$ROOT/src" -I"$SDL_SDK/include" \ + "${srcs[@]}" \ + "$SDL_SDK/build/libSDL3.a" -pthread -lm \ + -o "$OUT" + +if [[ ! -x "$OUT" && ! -f "$OUT" ]]; then + echo "FAIL: expected executable missing: $OUT" >&2 + exit 1 +fi + +echo "PASS built $OUT" >&2 diff --git a/tools/r0_5_synthetic_perf.py b/tools/r0_5_synthetic_perf.py new file mode 100755 index 00000000..8219213f --- /dev/null +++ b/tools/r0_5_synthetic_perf.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""R0.5 synthetic CPU/SDL performance baseline reproduction workflow. + +Generates synthetic fixtures, compiles benchmark binaries, runs CPU and SDL +(dummy/software) measurements, and writes logs/CSV under build/validation/R0.5/. +No owned Wolfenstein data, no network, no new dependencies. +""" +from __future__ import annotations +import argparse, os, shutil, subprocess, sys, time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from game_fixtures import game_files # noqa: E402 + +SDK_DEFAULT = ROOT.parent / "cart/vendor/SDL" +CC = os.environ.get("CC", "gcc") +CFLAGS = ["-std=c11", "-O2", "-Wall", "-Wextra", "-Wpedantic", "-Wconversion", "-Wshadow", "-Werror", "-g"] +LDFLAGS = ["-pthread", "-lm"] + + +def run(cmd, log_path: Path, timeout: int, env=None, cwd=ROOT): + log_path.parent.mkdir(parents=True, exist_ok=True) + print(f"START {log_path.name}: {' '.join(cmd)}", flush=True) + start = time.time() + with log_path.open("w", encoding="utf-8") as log: + log.write(f"COMMAND: {' '.join(cmd)}\n") + log.write(f"TIMEOUT: {timeout}s\n") + log.flush() + try: + proc = subprocess.run(cmd, cwd=cwd, env=env, stdout=log, stderr=subprocess.STDOUT, + text=True, timeout=timeout) + rc = proc.returncode + except subprocess.TimeoutExpired: + log.write("\nRESULT: TIMEOUT\n") + rc = 124 + log.write(f"EXIT: {rc}\n") + elapsed = time.time() - start + status = "PASS" if rc == 0 else "FAIL" + print(f"{status} {log_path.name} exit={rc} elapsed={elapsed:.1f}s", flush=True) + return rc + + +def compile_bench(sdk: Path, out: Path, extra_flags, sources, log_path: Path, timeout: int): + cmd = [CC, *CFLAGS, *extra_flags, "-I./src", f"-I{sdk/'include'}", + "tests/synthetic_perf_benchmark.c", *sources, + str(sdk / "build/libSDL3.a"), *LDFLAGS, "-o", str(out)] + return run(cmd, log_path, timeout) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--sdk", default=os.environ.get("SDL_SDK", str(SDK_DEFAULT)), + help="SDL3 SDK path (default: ../cart/vendor/SDL or $SDL_SDK)") + ap.add_argument("--out", default=str(ROOT / "build/validation/R0.5"), + help="Output directory for logs/data/binaries") + ap.add_argument("--timeout", type=int, default=600, help="Per-step timeout seconds") + args = ap.parse_args() + + sdk = Path(args.sdk) + out = Path(args.out) + logs = out / "logs" + data = out / "perf-data" + user_cpu = out / "perf-user" + user_sdl = out / "perf-user-sdl" + out.mkdir(parents=True, exist_ok=True) + logs.mkdir(parents=True, exist_ok=True) + + if not (sdk / "build/libSDL3.a").is_file(): + print(f"FAIL prerequisite missing SDL static lib: {sdk/'build/libSDL3.a'}", file=sys.stderr) + return 2 + if shutil.which(CC) is None: + print(f"FAIL prerequisite missing compiler: {CC}", file=sys.stderr) + return 2 + + # Synthetic data + if data.exists(): + shutil.rmtree(data) + data.mkdir(parents=True) + game_files(data) + print(f"PASS synthetic fixtures generated at {data}", flush=True) + + engine = sorted(str(p) for p in (ROOT / "src/engine").glob("*.c")) + platform = sorted(str(p) for p in (ROOT / "src/platform").glob("*.c")) + plat_min = [str(ROOT / "src/platform/data_file.c"), str(ROOT / "src/platform/save_file.c")] + + rc = 0 + cpu_bin = out / "synthetic_perf_bench" + sdl_bin = out / "synthetic_perf_bench_sdl" + rc |= compile_bench(sdk, cpu_bin, [], [*engine, *plat_min], logs / "perf-compile-cpu.log", args.timeout) + rc |= compile_bench(sdk, sdl_bin, ["-DWOLF3D_BENCHMARK"], [*engine, *platform], logs / "perf-compile-sdl.log", args.timeout) + if rc != 0: + print("FAIL compilation failed; see logs", file=sys.stderr) + return 1 + + if user_cpu.exists(): + shutil.rmtree(user_cpu) + user_cpu.mkdir(parents=True) + rc |= run([str(cpu_bin), str(data), str(user_cpu)], logs / "perf-cpu.stdout.log", args.timeout) + + if user_sdl.exists(): + shutil.rmtree(user_sdl) + user_sdl.mkdir(parents=True) + env = dict(os.environ) + env["SDL_VIDEODRIVER"] = "dummy" + env["SDL_RENDER_DRIVER"] = "software" + env["SDL_AUDIODRIVER"] = "dummy" + rc |= run([str(sdl_bin), str(data), str(user_sdl), "--sdl"], logs / "perf-sdl.stdout.log", args.timeout, env=env) + + # Extract CSV/META for convenience + for name in ["perf-cpu.stdout.log", "perf-sdl.stdout.log"]: + p = logs / name + csv = logs / name.replace(".stdout.log", ".csv") + if p.exists(): + rows = [l for l in p.read_text(encoding="utf-8", errors="replace").splitlines() + if l.startswith("CSV_HEADER,") or l.startswith("CSV,") or l.startswith("META,")] + csv.write_text("\n".join(rows) + ("\n" if rows else ""), encoding="utf-8") + print(f"PASS wrote {csv}", flush=True) + + summary = out / "perf-summary.txt" + lines = [f"R0.5 synthetic perf summary: {'PASS' if rc == 0 else 'FAIL'}\n"] + for p in [logs / "perf-cpu.csv", logs / "perf-sdl.csv"]: + if p.exists(): + lines.append(p.read_text(encoding="utf-8", errors="replace")) + summary.write_text("".join(lines), encoding="utf-8") + print(f"{'PASS' if rc == 0 else 'FAIL'} summary written to {summary}", flush=True) + return 0 if rc == 0 else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/test.sh b/tools/test.sh new file mode 100755 index 00000000..5894b820 --- /dev/null +++ b/tools/test.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +PYTHON="${PYTHON:-python3}" +RUNNER="$ROOT/tools/validation/run.py" + +usage() { + cat <<'EOF' +Usage: tools/test.sh [--graphics|--sanitizer|--performance|--all] [--milestone R0.x] [--dry-run] [--job ID] + +Lightweight wrapper around tools/validation/run.py. + (no args) Run R0.6 mandatory synthetic validation (default) + --graphics Run graphics-category jobs (default milestone R0.4) + --sanitizer Run sanitizer-category jobs (default milestone R0.5) + --performance Run performance-category jobs (default milestone R0.5) + --all Run all milestone jobs + --milestone R0.x Select milestone explicitly + --dry-run Print selected jobs without executing + --job ID Run a specific job id (repeatable) + -h, --help Show help +EOF +} + +milestone="" +categories=() +jobs=() +dry_run=0 +all=0 + +while [[ $# -gt 0 ]]; do + case "$1" in + --graphics) categories+=(--category graphics); [[ -z "$milestone" ]] && milestone="R0.4" ;; + --sanitizer) categories+=(--category sanitizer); [[ -z "$milestone" ]] && milestone="R0.5" ;; + --performance) categories+=(--category performance); [[ -z "$milestone" ]] && milestone="R0.5" ;; + --all) all=1; milestone="all" ;; + --milestone) shift; milestone="${1:-}" ;; + --dry-run) dry_run=1 ;; + --job) shift; jobs+=(--job "${1:-}") ;; + -h|--help) usage; exit 0 ;; + *) echo "Unknown argument: $1" >&2; usage >&2; exit 2 ;; + esac + shift +done + +if [[ $all -eq 0 && -z "$milestone" ]]; then + milestone="R0.6" +fi + +cmd=("$PYTHON" "$RUNNER" "$milestone") +if [[ ${#categories[@]} -gt 0 ]]; then cmd+=("${categories[@]}"); fi +if [[ ${#jobs[@]} -gt 0 ]]; then cmd+=("${jobs[@]}"); fi +if [[ $dry_run -eq 1 ]]; then cmd+=(--dry-run); fi + +echo "+ ${cmd[*]}" >&2 +exec "${cmd[@]}" diff --git a/tools/validation/run.py b/tools/validation/run.py new file mode 100644 index 00000000..e984805a --- /dev/null +++ b/tools/validation/run.py @@ -0,0 +1,614 @@ +#!/usr/bin/env python3 +"""Unified R0 validation runner. + +Lightweight orchestrator over existing Python unittest suites and scripts. +No third-party dependencies. Writes logs + JSON summary under build/validation/. +""" +from __future__ import annotations + +import argparse +import json +import os +import platform +import shutil +import signal +import subprocess +import sys +import time +from dataclasses import asdict, dataclass, field +from datetime import datetime, timezone +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +BUILD_VALIDATION = ROOT / "build" / "validation" +PY = sys.executable + + +@dataclass +class Job: + id: str + milestone: str # primary milestone + milestones: tuple[str, ...] # milestones that include this job + description: str + command: list[str] + timeout: int + mandatory: bool = True + category: str = "cpu" # cpu|graphics|sanitizer|performance|meta + env: dict[str, str] = field(default_factory=dict) + requires: tuple[str, ...] = () # e.g. "sdl-sdk","cc" + notes: str = "" + + +@dataclass +class JobResult: + id: str + milestone: str + description: str + command: list[str] + category: str + mandatory: bool + timeout: int + status: str # PASS|FAIL|TIMEOUT|SKIP|NOT RUN + exit_code: int | None + duration_s: float + started_at: str + ended_at: str + log_file: str + message: str = "" + + +def _utcnow(): + return datetime.now(timezone.utc).isoformat() + + +def _run_id(): + return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + + +def _display_path(p: Path) -> str: + try: + return str(p.resolve().relative_to(ROOT.resolve())) + except Exception: + return str(p) + + +def _has_sdl_sdk() -> bool: + sdk = Path(os.environ.get("SDL_SDK", ROOT.parent / "cart/vendor/SDL")) + return (sdk / "build/libSDL3.a").is_file() or (sdk / "include/SDL3/SDL.h").is_file() + + +def _has_cc() -> bool: + return shutil.which(os.environ.get("CC", "gcc")) is not None + + +def _prereq_missing(job: Job) -> str | None: + for req in job.requires: + if req == "sdl-sdk" and not _has_sdl_sdk(): + return f"missing prerequisite: SDL SDK (set SDL_SDK or build ../cart/vendor/SDL)" + if req == "cc" and not _has_cc(): + return f"missing prerequisite: C compiler ({os.environ.get('CC','gcc')})" + if req == "asan": + # Best-effort check: gcc present; actual runtime checked by test run. + if not _has_cc(): + return "missing prerequisite: C compiler for ASan/UBSan" + return None + + +def build_jobs() -> list[Job]: + env_base = {} + sdl_env = { + "SDL_VIDEODRIVER": "dummy", + "SDL_RENDER_DRIVER": "software", + "SDL_AUDIODRIVER": "dummy", + } + sanitize_env = {"SANITIZE": "1"} + + jobs: list[Job] = [] + + # R0.3 - deterministic headless CPU harness + jobs.append(Job( + id="r03-engine-synthetic", + milestone="R0.3", + milestones=("R0.3", "R0.6", "all"), + description="Engine synthetic/headless unit tests (R0.3 scope; owned-data cases may skip)", + command=[PY, "-m", "unittest", "discover", "-s", "tests", "-p", "test_engine.py", "-v"], + timeout=900, + mandatory=True, + category="cpu", + env=env_base, + )) + + # R0.4 - matched render baselines / graphics + for tid, desc, timeout in [ + ("r04-render", "Render synthetic baseline and comparator tests", 600), + ("r04-display", "Display/presentation geometry tests", 600), + ("r04-presentation", "Presentation timing/interpolation tests", 600), + ("r04-classic", "Classic renderer/view tests", 600), + ]: + p = tid.replace("r04-", "test_") + ".py" + jobs.append(Job( + id=tid, + milestone="R0.4", + milestones=("R0.4", "R0.6", "all"), + description=desc, + command=[PY, "-m", "unittest", "discover", "-s", "tests", "-p", p, "-v"], + timeout=timeout, + mandatory=True, + category="graphics", + env=sdl_env, + requires=("sdl-sdk", "cc"), + )) + + # R0.5 - sanitizer suites (representative instrumented harness coverage) + sanitizer_tests = [ + ("r05-san-engine", "test_engine.py", 1200, "Sanitizer: engine/lifecycle/resource harnesses"), + ("r05-san-render", "test_render.py", 1200, "Sanitizer: render Classic/Enhanced harnesses"), + ("r05-san-classic", "test_classic.py", 1200, "Sanitizer: classic renderer harnesses"), + ("r05-san-display", "test_display.py", 1200, "Sanitizer: display lifecycle harnesses"), + ("r05-san-presentation", "test_presentation.py", 1200, "Sanitizer: presentation/frame-clock harnesses"), + ("r05-san-save", "test_save.py", 1200, "Sanitizer: save/resource harnesses"), + ("r05-san-config", "test_config.py", 1200, "Sanitizer: config resource harnesses"), + ("r05-san-controls", "test_controls.py", 900, "Sanitizer: controls harnesses"), + ("r05-san-loading", "test_loading.py", 900, "Sanitizer: loading harnesses"), + ("r05-san-audio", "test_audio.py", 900, "Sanitizer: audio harnesses"), + ("r05-san-signon", "test_signon.py", 900, "Sanitizer: signon harnesses"), + ("r05-san-dos-menus", "test_dos_menus.py", 900, "Sanitizer: DOS menu harnesses"), + ("r05-san-dos-ui-reference", "test_dos_ui_reference.py", 900, "Sanitizer: DOS UI reference harnesses"), + ("r05-san-demo-sync", "test_demo_sync.py", 1200, "Sanitizer: demo sync harnesses"), + ] + for jid, pat, timeout, desc in sanitizer_tests: + jobs.append(Job( + id=jid, + milestone="R0.5", + milestones=("R0.5", "all"), + description=desc, + command=[PY, "-m", "unittest", "discover", "-s", "tests", "-p", pat, "-v"], + timeout=timeout, + mandatory=True, + category="sanitizer", + env={**sdl_env, **sanitize_env}, + requires=("sdl-sdk", "cc", "asan"), + notes="Instrumented C harnesses only where wrappers compile with SANITIZE=1; prebuilt WOLF3D_BINARY subprocesses are not ASan-instrumented.", + )) + + # R0.5 performance + jobs.append(Job( + id="r05-perf-synthetic", + milestone="R0.5", + milestones=("R0.5", "all"), + description="Synthetic CPU/SDL performance baseline (evidence, no FPS gate)", + command=[PY, "tools/r0_5_synthetic_perf.py", "--timeout", "600"], + timeout=1200, + mandatory=True, + category="performance", + env=sdl_env, + requires=("sdl-sdk", "cc"), + notes="Performance is evidence; no target FPS pass/fail gate is applied.", + )) + + # R0.6 - validation runner tests + jobs.append(Job( + id="r06-runner-tests", + milestone="R0.6", + milestones=("R0.6", "all"), + description="Validation runner orchestration unit tests", + command=[PY, "-m", "unittest", "discover", "-s", "tests", "-p", "test_validation_runner.py", "-v"], + timeout=300, + mandatory=True, + category="meta", + )) + + return jobs + + +STATUS_PASS = "PASS" +STATUS_FAIL = "FAIL" +STATUS_TIMEOUT = "TIMEOUT" +STATUS_SKIP = "SKIP" +STATUS_NOT_RUN = "NOT RUN" + + +def select_jobs(jobs: list[Job], milestone: str, categories: set[str] | None = None) -> list[Job]: + m = milestone.upper() + selected = [j for j in jobs if m in [x.upper() for x in j.milestones] or m == "ALL" and "all" in [x.lower() for x in j.milestones]] + if categories: + selected = [j for j in selected if j.category in categories] + # de-duplicate by id preserving order + seen = set() + out = [] + for j in selected: + if j.id not in seen: + seen.add(j.id) + out.append(j) + return out + + +def _pgid_alive(pgid: int) -> bool: + """Return whether a process group has a non-zombie member.""" + members = _process_group_members(pgid) + if members is not None: + return bool(members) + try: + os.killpg(pgid, 0) + return True + except ProcessLookupError: + return False + except PermissionError: + return True + except Exception: + return False + + +def _process_info(pid: int) -> tuple[str, int, int, int] | None: + """Return Linux process state, pgrp, session and start ticks.""" + try: + stat = (Path("/proc") / str(pid) / "stat").read_text(encoding="utf-8") + fields = stat[stat.rfind(")") + 2:].split() + return fields[0], int(fields[2]), int(fields[3]), int(fields[19]) + except (FileNotFoundError, ProcessLookupError, PermissionError, ValueError, IndexError): + return None + + +_IDENTITY_UNSET = object() + + +def _process_group_members(pgid: int, leader_start=_IDENTITY_UNSET) -> list[tuple[int, int]] | None: + """List non-zombie members as (pid,start_ticks), or None without /proc. + + A live process at the captured leader PID with a different start time means + the PID/process-group ID was reused; cleanup must not signal that group. + """ + procfs = Path("/proc") + if not procfs.is_dir(): + return None + leader = _process_info(pgid) + if leader_start is None and leader is not None: + # The observed leader cannot be tied to this launch. Refuse to inspect + # or signal a potentially reused process-group identity. + return [] + if isinstance(leader_start, int) and leader is not None and leader[3] != leader_start: + return [] + members: list[tuple[int, int]] = [] + for entry in procfs.iterdir(): + if not entry.name.isdigit(): + continue + pid = int(entry.name) + info = _process_info(pid) + if info is None: + continue + state, pgrp, session, start = info + if pgrp == pgid and session == pgid and state != "Z": + members.append((pid, start)) + return members + + +def _group_alive(pgid: int, leader_start: int | None) -> bool: + members = _process_group_members(pgid, leader_start) + return _pgid_alive(pgid) if members is None else bool(members) + + +def _signal_group(pgid: int, leader_start: int | None, sig: int) -> None: + members = _process_group_members(pgid, leader_start) + if members is None: + if _pgid_alive(pgid): + try: + os.killpg(pgid, sig) + except (ProcessLookupError, PermissionError): + pass + return + # Re-check every captured identity immediately before signalling it. This + # avoids signalling a process that reused a descendant PID. + for pid, start in members: + info = _process_info(pid) + if info is None or info[3] != start or info[0] == "Z": + continue + try: + os.kill(pid, sig) + except (ProcessLookupError, PermissionError): + pass + + +def _wait_group_gone(pgid: int, leader_start: int | None, timeout: float) -> bool: + deadline = time.monotonic() + timeout + while _group_alive(pgid, leader_start) and time.monotonic() < deadline: + time.sleep(0.02) + return not _group_alive(pgid, leader_start) + + +def _post_exit_group_members(pgid: int, leader_start: int | None, + timeout: float = 0.2) -> list[tuple[int, int]]: + """Observe a newly exited parent's group through a bounded settle window.""" + deadline = time.monotonic() + timeout + while True: + members = _process_group_members(pgid, leader_start) + if members is None: + return [(-1, 0)] if _pgid_alive(pgid) else [] + if members or time.monotonic() >= deadline: + return members + time.sleep(0.01) + + +def kill_process_group(proc: subprocess.Popen, pgid: int | None = None, + leader_start: int | None = None) -> None: + """Bounded TERM-to-KILL cleanup of the captured job process group. + + Zombies are considered finished. On Linux, process start times are rechecked + before signalling so reused IDs are not targeted. + """ + if pgid is None: + pgid = proc.pid + if leader_start is None: + info = _process_info(pgid) + leader_start = info[3] if info is not None else None + + _signal_group(pgid, leader_start, signal.SIGTERM) + if not _wait_group_gone(pgid, leader_start, 1.0): + _signal_group(pgid, leader_start, signal.SIGKILL) + _wait_group_gone(pgid, leader_start, 1.0) + try: + proc.wait(timeout=1) + except subprocess.TimeoutExpired: + try: + proc.kill() + except (ProcessLookupError, PermissionError): + pass + try: + proc.wait(timeout=1) + except (subprocess.TimeoutExpired, ProcessLookupError): + pass + + +def run_job(job: Job, run_dir: Path) -> JobResult: + log_path = run_dir / f"{job.id}.log" + log_path.parent.mkdir(parents=True, exist_ok=True) + started = time.time() + started_at = _utcnow() + print(f"START [{job.milestone}] {job.id}: {job.description}", flush=True) + print(f" timeout={job.timeout}s cmd={' '.join(job.command)}", flush=True) + + prereq = _prereq_missing(job) + if prereq: + status = STATUS_NOT_RUN if job.mandatory else STATUS_SKIP + ended_at = _utcnow() + msg = prereq + log_path.write_text(f"{msg}\n", encoding="utf-8") + print(f"{status} [{job.milestone}] {job.id} ({msg})", flush=True) + return JobResult(job.id, job.milestone, job.description, job.command, job.category, + job.mandatory, job.timeout, status, None, 0.0, started_at, ended_at, + _display_path(log_path), msg) + + env = os.environ.copy() + env.update(job.env) + # Never allow baseline updates from validation runner + env.pop("WOLF3D_UPDATE_BASELINES", None) + + header = [ + f"job={job.id}", + f"milestone={job.milestone}", + f"description={job.description}", + f"timeout={job.timeout}", + f"command={' '.join(job.command)}", + f"started_at={started_at}", + "", + ] + exit_code: int | None = None + status = STATUS_FAIL + message = "" + timed_out = False + + with log_path.open("w", encoding="utf-8") as log: + log.write("\n".join(header)) + log.flush() + try: + proc = subprocess.Popen( + job.command, + cwd=ROOT, + env=env, + stdout=log, + stderr=subprocess.STDOUT, + text=True, + start_new_session=True, + ) + except Exception as e: + ended_at = _utcnow() + duration = time.time() - started + msg = f"failed to start: {e}" + log.write(msg + "\n") + print(f"FAIL [{job.milestone}] {job.id} ({msg})", flush=True) + return JobResult(job.id, job.milestone, job.description, job.command, job.category, + job.mandatory, job.timeout, STATUS_FAIL, None, duration, started_at, ended_at, + _display_path(log_path), msg) + pgid = proc.pid + leader_info = _process_info(pgid) + leader_start = leader_info[3] if leader_info is not None else None + unexpected_descendants: list[int] = [] + try: + proc.wait(timeout=job.timeout) + except subprocess.TimeoutExpired: + timed_out = True + kill_process_group(proc, pgid, leader_start) + try: + proc.wait(timeout=5) + except Exception: + pass + except KeyboardInterrupt: + kill_process_group(proc, pgid, leader_start) + try: + proc.wait(timeout=5) + except Exception: + pass + raise + # A zero-exit parent is not successful while unexpected descendants are + # still running. Record the incomplete tree before bounded cleanup. + if not timed_out: + members = _post_exit_group_members(pgid, leader_start) + unexpected_descendants = [pid for pid, _ in members if pid != proc.pid] + if unexpected_descendants: + kill_process_group(proc, pgid, leader_start) + + exit_code = proc.returncode + if timed_out: + status = STATUS_TIMEOUT + message = f"timed out after {job.timeout}s" + log.write(f"\nRESULT: TIMEOUT after {job.timeout}s\n") + elif unexpected_descendants: + status = STATUS_FAIL + detail = "unknown" if unexpected_descendants == [-1] else ",".join(map(str, unexpected_descendants)) + message = f"parent exit {exit_code}; cleaned surviving descendants pids={detail}" + log.write(f"\nRESULT: FAIL {message}\n") + elif exit_code == 0: + status = STATUS_PASS + log.write("\nRESULT: PASS\n") + else: + status = STATUS_FAIL + message = f"exit {exit_code}" + log.write(f"\nRESULT: FAIL exit={exit_code}\n") + + ended_at = _utcnow() + duration = time.time() - started + print(f"{status} [{job.milestone}] {job.id} exit={exit_code} duration={duration:.1f}s" + (f" ({message})" if message else ""), flush=True) + return JobResult(job.id, job.milestone, job.description, job.command, job.category, + job.mandatory, job.timeout, status, exit_code, duration, started_at, ended_at, + _display_path(log_path), message) + + +def overall_status(results: list[JobResult]) -> str: + if not results: + return STATUS_FAIL + for r in results: + if r.mandatory and r.status in (STATUS_FAIL, STATUS_TIMEOUT, STATUS_NOT_RUN): + return STATUS_FAIL + if r.mandatory and r.status == STATUS_SKIP: + # mandatory skip is treated as failure unless explicitly not possible - be conservative + return STATUS_FAIL + # All mandatory jobs passed + if any(r.status == STATUS_PASS for r in results): + return STATUS_PASS + return STATUS_FAIL + + +def write_summary(run_dir: Path, milestone: str, results: list[JobResult], started_at: str, ended_at: str) -> Path: + summary = { + "schema_version": 1, + "milestone": milestone, + "started_at": started_at, + "ended_at": ended_at, + "duration_s": sum(r.duration_s for r in results), + "overall_status": overall_status(results), + "environment": { + "platform": platform.platform(), + "python": sys.version.split()[0], + "cwd": str(ROOT), + "cc": shutil.which(os.environ.get("CC", "gcc")) or "", + }, + "jobs": [asdict(r) for r in results], + } + path = run_dir / "summary.json" + path.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8") + return path + + +def print_summary(results: list[JobResult], summary_path: Path) -> None: + counts = {} + for r in results: + counts[r.status] = counts.get(r.status, 0) + 1 + overall = overall_status(results) + print("\n=== Validation summary ===", flush=True) + for r in results: + flag = "*" if r.mandatory else " " + print(f" {flag} {r.status:7s} {r.id:28s} {r.duration_s:7.1f}s exit={r.exit_code} {r.log_file}", flush=True) + print(f"--- counts: {counts}", flush=True) + print(f"--- overall: {overall}", flush=True) + print(f"--- summary: {summary_path.relative_to(ROOT)}", flush=True) + + +def parse_args(argv: list[str]) -> argparse.Namespace: + ap = argparse.ArgumentParser(description="Run Wolf3D Revive milestone validation jobs.") + ap.add_argument("milestone", nargs="?", help="Milestone to run: R0.3, R0.4, R0.5, R0.6, all") + ap.add_argument("--list", action="store_true", help="List jobs and exit") + ap.add_argument("--dry-run", action="store_true", help="Select and print jobs without executing") + ap.add_argument("--category", action="append", choices=["cpu", "graphics", "sanitizer", "performance", "meta"], + help="Only run jobs in selected category (repeatable)") + ap.add_argument("--run-id", help="Override run id (default: UTC timestamp)") + ap.add_argument("--out-root", default=str(BUILD_VALIDATION), help="Validation output root") + ap.add_argument("--job", action="append", dest="jobs", help="Run only specific job id(s) (repeatable)") + args = ap.parse_args(argv) + if not args.list and not args.milestone: + ap.error("milestone is required unless --list is used") + return args + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv if argv is not None else sys.argv[1:]) + jobs = build_jobs() + known_milestones = {"R0.3", "R0.4", "R0.5", "R0.6", "ALL"} + + if args.list: + for j in jobs: + ms = ",".join(j.milestones) + mand = "mandatory" if j.mandatory else "optional" + print(f"{j.id:28s} {j.milestone:5s} {j.category:11s} {mand:9s} timeout={j.timeout:4d}s [{ms}] {j.description}") + return 0 + + milestone = args.milestone.upper() + if milestone not in known_milestones: + print(f"FAIL unknown milestone: {args.milestone}. Expected one of {sorted(known_milestones)}", file=sys.stderr) + return 2 + + categories = set(args.category) if args.category else None + selected = select_jobs(jobs, milestone, categories) + if args.jobs: + wanted = set(args.jobs) + selected = [j for j in selected if j.id in wanted] + missing = wanted - {j.id for j in selected} + if missing: + print(f"FAIL unknown/unselcted job id(s): {sorted(missing)}", file=sys.stderr) + return 2 + if not selected: + print("FAIL no jobs selected", file=sys.stderr) + return 2 + + run_id = args.run_id or _run_id() + run_dir = Path(args.out_root) / milestone / run_id + run_dir.mkdir(parents=True, exist_ok=True) + + print(f"=== Validation run {milestone} run_id={run_id} ===", flush=True) + print(f"output={run_dir.relative_to(ROOT)} jobs={len(selected)}", flush=True) + for j in selected: + mand = "mandatory" if j.mandatory else "optional" + print(f" - {j.id} [{j.category}/{mand}] timeout={j.timeout}s :: {j.description}", flush=True) + + if args.dry_run: + return 0 + + started_at = _utcnow() + results: list[JobResult] = [] + try: + for j in selected: + results.append(run_job(j, run_dir)) + except KeyboardInterrupt: + print("FAIL interrupted", file=sys.stderr) + # mark remaining as NOT RUN + done = {r.id for r in results} + now = _utcnow() + for j in selected: + if j.id in done: + continue + lp = run_dir / f"{j.id}.log" + lp.write_text("NOT RUN: interrupted\n", encoding="utf-8") + results.append(JobResult(j.id, j.milestone, j.description, j.command, j.category, + j.mandatory, j.timeout, STATUS_NOT_RUN, None, 0.0, now, now, + str(lp.relative_to(ROOT)), "interrupted")) + ended_at = _utcnow() + sp = write_summary(run_dir, milestone, results, started_at, ended_at) + print_summary(results, sp) + return 130 + + ended_at = _utcnow() + summary_path = write_summary(run_dir, milestone, results, started_at, ended_at) + print_summary(results, summary_path) + return 0 if overall_status(results) == STATUS_PASS else 1 + + +if __name__ == "__main__": + raise SystemExit(main())